prevState
是您为传递给 setState 回调函数的参数指定的名称。它保存的是setState
React 触发之前 state 的值;由于进行setState
批处理,因此当您想根据先前的状态值更新新状态时,了解先前的状态有时很重要。
因此,如果多个 setState 调用正在更新同一状态,则批处理 setState 调用可能会导致设置不正确的状态。考虑一个例子:
state = {
count: 0
}
updateCount = () => {
this.setState({ count: this.state.count + 1});
this.setState({ count: this.state.count + 1});
this.setState({ count: this.state.count + 1});
this.setState({ count: this.state.count + 1});
}
在上面的代码中,您可能期望 count 的值为 4,但实际上它是 1,因为最后一次调用 setState 将在批处理期间覆盖任何先前的值。解决此问题的方法是使用功能性 setState:
updateCount = () => {
this.setState(prevstate => ({ count: prevstate.count + 1}));
this.setState(prevstate => ({ count: prevstate.count + 1}));
this.setState(prevstate => ({ count: prevstate.count + 1}));
this.setState(prevstate => ({ count: prevstate.count + 1}));
}