我阅读了很多关于使用这样的功能的文章setState
:
this.setState((state, props) => ({ counter: state.counter + props.increment }));
但是我们什么时候真正需要将它用作这样的对象:
this.setState({quantity: 2})
为什么我们应该setState
在正常情况下使用对象而不是将其用作函数,是否有重要原因?
规范是使用一个对象,它的代码也更少,更容易阅读。你想要使用函数 setState 的唯一原因是当你需要访问以前的状态时。
考虑下面的例子
// you have a switch state
state = {
checked: false
}
// .. and later in an onChange method
onChange = () => {
const {checked} = this.state;
// this is problematic because react works in an async fashion, so it could be that when this function was called checked was false, however it was only executed later when checked was actually true
this.setState({checked: !checked}
// on the other hand this form is safe, even if things were happening async, you are safe because you act on the most updated state
this.setState(prvState => {...prvState, checked: !prvState.checked})
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句