慕神8447489
2022-12-09 19:02:07
我正在完成 FreeCodeCamp React 練習,其中有一個簡單的遞增和遞減狀態初始化的計數值。如果我使用傳統函數編寫方法,它工作正常:increment() { this.setState({ count: this.state.count + 1 });}decrement() { this.setState({ count: this.state.count - 1 });}reset() { this.setState({ count: this.state.count = 0 });} 但是如果我使用箭頭函數,它就會停止工作。“重置”按鈕不是重置為零,而是以與“減少”按鈕相同的方式減少值?!斑f增”和“遞減”工作顯然正常。increment = () => { this.setState({ count: this.state.count + 1 });} decrement = () => { this.setState({ count: this.state.count - 1 });} reset = () => { this.setState({ count: this.state.count = 0 });}我在這里遺漏了一個細節。一些同事能告訴我為什么函數表達式在這種情況下不起作用嗎?提前致謝。
2 回答

慕尼黑的夜晚無繁華
TA貢獻1864條經驗 獲得超6個贊
箭頭函數不同于常規函數
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
簡而言之,'this' 的值在常規函數和 lambda 函數中是不一樣的。
只是為了增加一點精度,您可能使用了 .bind(),因此,使用了兩個函數(一個常規函數和一個返回 this 的箭頭,并嘗試綁定它們,我們得到:
const f=function() { return this; };
const bf=f.bind({});
console.log(bf()); // correctly binds 'this' to the provided object
const l=()=>this;
const bl=l.bind({});
console.log(bl()); // didn't bind, returned window
添加回答
舉報
0/150
提交
取消