问题描述
我认为问这个问题可能很愚蠢,但相信我,我是 reactJS 的初学者.有人可以解释一下为什么我们在 ReactjS 中使用 prevState .我努力去理解但失败了.
I think it might be silly question to ask but trust me I am beginner to reactJS . Could someone please explain me why we use prevState in ReactjS . I tried hard to understand but failed .
这是我的代码.请帮我理解
state = {
placeName : '',
places : []
}
placeSubmitHanlder = () => {
if(this.state.placeName.trim()===''){
return;
}
this.setState(prevState => {
return {
places : prevState.places.concat(prevState.placeName)
};
});
};
推荐答案
prevState
是您为传递给 setState 回调函数的参数指定的名称.它保存的是 setState
被 React 触发之前的 state 值;由于 setState
进行批处理,因此当您想根据之前的状态值更新新状态时,了解之前的状态有时很重要.
prevState
is a name that you have given to the argument passed to setState callback function. What it holds is the value of state before the setState
was triggered by React; Since setState
does batching, its sometimes important to know what the previous state was when you want to update the new state based on the previous state value.
因此,如果多个 setState 调用正在更新同一状态,则批处理 setState 调用可能会导致设置不正确的状态.考虑一个例子:
So if multiple setState calls are updating the same state, batching setState calls may lead to incorrect state being set. Consider an example:
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 解决此问题的方法:
In the above code you might expect the value of count to be 4 but it would actually be 1 since the last call to setState will override any previous value during batching. A way to solve this to use functional 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}));
}
这篇关于ReactJS 中的 prevState 是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!