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

慕尼黑的夜晚無繁華
TA貢獻1864條經(jīng)驗 獲得超6個贊
箭頭函數(shù)不同于常規(guī)函數(shù)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
簡而言之,'this' 的值在常規(guī)函數(shù)和 lambda 函數(shù)中是不一樣的。
只是為了增加一點精度,您可能使用了 .bind(),因此,使用了兩個函數(shù)(一個常規(guī)函數(shù)和一個返回 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
提交
取消