我目前正在学习 React,但我不完全明白为什么这是错误的:
// Wrong
this.setState({
counter: this.state.counter + this.props.increment,
});
这是正确的:
// Correct
this.setState((state, props) => ({
counter: state.counter + props.increment
}));
有人能给我一个真实世界的例子吗?我可以使用接受函数的“第二种形式的 setState()
”?
这是link
最佳答案
假设您有一个 CheckBoxComponent
,您可以在构造函数中像这样初始化其状态:
this.state = {启用:true}
您希望在用户单击复选框时更新其状态。所以你编写了这个点击处理程序:
function toggleCheckbox() {
this.setState({enabled: ???});
}
第二种setState就是针对这种情况的。点击处理程序应写为:
function toggleCheckbox() {
this.setState(prevState => ({enabled: !prevState.enabled}));
}
关于javascript - 我需要澄清 react 的状态和生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53825127/