问题描述
我是React的新手,只是对setState方法有疑问.假设我们有一个组件:
I'm new to React, just have a question on setState method. Let's say we have a component:
class MyApp extends React.Component {
state = {
count: 3
};
Increment = () => {
this.setState((prevState) => ({
options: prevState.count + 1)
}));
}
}
那么为什么我们必须在setState方法中使用prevState?为什么我们不能这样做:
so why we have to use prevState in the setState method? why can't we just do:
this.setState(() => ({
options: this.state.count + 1)
}));
推荐答案
两个签名都可以使用,唯一的区别是,如果需要根据先前的状态更改状态,则应使用 this.setState(函数)
,它将为您提供前一个状态的快照( prevState
).但是,如果更改不依赖于其他任何先前的值,则建议使用较短的版本 this.setState({prop:newValue})
Both signatures can be used, the only difference is that if you need to change your state based on the previous state you should use this.setState(function)
which will provide you a snapshot(prevState
) from the previous state. But if the change does not rely on any other previous value, then a shorter version is recommended this.setState({prop: newValue})
this.setState(prevState =>{
return{
...prevState,
counter : prevState.counter +1
}
})
this.setState({counter : 2})
这篇关于使用prevState参数的React的setState方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!