[英]Updater function syntax with React setState
I usually update state in react to toggle a icon display in react: 我通常在react中更新状态以在react中切换图标显示:
toggle = () => {
this.setState({
open: !this.state.open
}) // setState
} // toggle callback
Now I saw a new way of doing it, which is recommended over the above way: 现在,我看到了一种新的执行方法,在上述方法中,建议您这样做:
toggle = () => {
this.setState((prevState, props) => {
return {
open: !prevState.open
} // return
}) // setState
} // toggle callback
In this case, the setState function consumes a updater(which in this case is a callback function), which worked. 在这种情况下,setState函数使用一个有效的更新程序(在本例中为回调函数)。 how does the setState function consumes the updater?
setState函数如何消耗更新程序? The second parameter in updater
props
was not even used, what is the use of it? updater
props
的第二个参数甚至都没有使用,它的用途是什么?
In your case, you may omit the second parameter to the setState, 根据您的情况,您可以将第二个参数省略为setState,
toggle = () => {
this.setState((prevState) => {
return {
open: !prevState.open
}
})
}
However, its useful when you want to update the state based on both the current props
and the prevState
value. 但是,当您要基于
current props
prevState
和prevState
值更新状态时,它很有用。
Also 也
(prevState) => {
return {
open: !prevState.open
}
}
is not a callback, but an updater function. 不是回调,而是更新程序功能。 According to the React docs:
根据React docs:
The first argument is an updater function with the signature:
第一个参数是带有签名的updater函数:
(prevState, props) => stateChange
prevState
is a reference to the previous state.prevState
是对先前状态的引用。 It should not be directly mutated.它不应该直接突变。 Instead, changes should be represented by building a new object based on the input from
prevState and prop
s.相反,更改应通过基于
prevState and prop
的输入构建一个新对象来表示。 For instance, suppose we wanted to increment a value in state byprops.step:
例如,假设我们想通过
props.step:
增加state的props.step:
this.setState((prevState, props) => { return {counter: prevState.counter + props.step}; });
Both
prevState
and props received by the updater function are guaranteed to be up-to-date.更新器功能接收到的
prevState
和props都保证是最新的。 The output of the updater is shallowly merged withprevState
.更新程序的输出与
prevState
浅层合并。
Also refer to this answer on Stackoverflow to see what a setState callback is useful for, 另请参阅Stackoverflow上的此答案,以了解setState回调的用途,
I want to add more information why using a callback function in setState
should be recommended. 我想添加更多信息,为什么应该建议在
setState
使用回调函数。
setState is asynchronous
setState是异步的
React batches state changes for performance, so that your state
may not change immediately after setState
. 为了提高性能,React批处理状态发生变化,因此您的
state
可能不会在setState
之后立即更改。 That means you should not rely on the current state
when calling setState
because you cannot be sure what that state will be! 这意味着您在调用
setState
时不应依赖当前state
,因为您无法确定该状态将是什么!
Moreover, your syntax could be simply 而且,您的语法可能很简单
this.setState(prevState => ({ open: !prevState.open }))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.