反应 setState 语法
React setState syntax
我的问题很直接,我发现状态在像这样的几个地方被更新,我想知道为什么我们要使用这种语法:
const showFlagRev = this.state.showFlag;
this.setState({showFlag: !showFlagRev});
通过这种语法:
this.setState(prevState => ({showFlag: !prevState.showFlagRev}));
这有什么原因吗?或者这只是一种在 React 应用程序中更新状态的旧方法(也许更清楚?)?
非常感谢任何参考资料(文档、文章、示例)!
来自docs:
This form of setState()
is also asynchronous, and multiple calls during the same cycle may be batched together. For example, if you attempt to increment an item quantity more than once in the same cycle, that will result in the equivalent of:
Object.assign(
previousState,
{quantity: state.quantity + 1},
{quantity: state.quantity + 1},
...
)
Subsequent calls will override values from previous calls in the same cycle, so the quantity will only be incremented once. If the next state depends on the current state, we recommend using the updater function form, instead:
this.setState((state) => {
return {quantity: state.quantity + 1};
});
我的问题很直接,我发现状态在像这样的几个地方被更新,我想知道为什么我们要使用这种语法:
const showFlagRev = this.state.showFlag;
this.setState({showFlag: !showFlagRev});
通过这种语法:
this.setState(prevState => ({showFlag: !prevState.showFlagRev}));
这有什么原因吗?或者这只是一种在 React 应用程序中更新状态的旧方法(也许更清楚?)?
非常感谢任何参考资料(文档、文章、示例)!
来自docs:
This form of
setState()
is also asynchronous, and multiple calls during the same cycle may be batched together. For example, if you attempt to increment an item quantity more than once in the same cycle, that will result in the equivalent of:
Object.assign(
previousState,
{quantity: state.quantity + 1},
{quantity: state.quantity + 1},
...
)
Subsequent calls will override values from previous calls in the same cycle, so the quantity will only be incremented once. If the next state depends on the current state, we recommend using the updater function form, instead:
this.setState((state) => {
return {quantity: state.quantity + 1};
});