简体   繁体   English

为什么 setstate 回调函数需要是箭头函数?

[英]why does the setstate callback function need to be an arrow function?

take this scenario采取这个场景

this.setState({ number: newNumber}, () => console.log(number))

and then this one:然后是这个:

this.setState({ number: newNumber}, console.log(number))

the first one (with the arrow) correctly logs the new state, the second (without the arrow) seems to console.log it one step behind.第一个(带箭头)正确记录了新状态,第二个(没有箭头)似乎在 console.log 后面一步。

why does the arrow function cause it to be correct in the setState callback?为什么箭头函数导致它在 setState 回调中是正确的?

Because, the second parameter inside setState is a callback function .因为, setState的第二个参数是回调函数 But this is not a callback:但这不是回调:

console.log(number)

Like the first answer, you need a callback function.像第一个答案一样,您需要一个回调函数。 console.log() is not a callback function if you don't wrap it inside a function.如果您不将其包装在函数中,则console.log()不是回调函数。

the second (without the arrow) seems to console.log it one step behind.第二个(没有箭头)似乎在 console.log 后面一步。

Instead of being a callback, console.log() is executed immediately, logs the current value of number variable and passes its return value as the callback argument. console.log()不是回调,而是立即执行,记录number变量的当前值并将其返回值作为回调参数传递。

You call console.log(number) at您调用console.log(number)

this.setState({ number: newNumber}, console.log(number))

and passes undefined as a callback.并将 undefined 作为回调传递。 Since console.log() returns undefined.由于 console.log() 返回未定义。 Such that this.setState becomes这样this.setState就变成了

this.setState({number: newNumber}, undefined);

this.setState() might have some sort of flag to not execute a callback function in cases where the callback parameter is not supplied (undefined is the same as not being supplied in terms of parameters), which explains why it's not throwing an error at undefined() . this.setState()可能有某种标志,在没有提供回调参数的情况下不执行回调函数(未定义与没有提供参数相同),这解释了为什么它不会在undefined()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM