[英]this.setState inside the callback of this.setState not setting state
我有 2 个列表项,它们使用与this.props.a = true
和this.props.b = true
相同的<ListItem />
组件从父组件传递给它(提到有 2 个,因为我不确定是否会混淆除了它们每个都应该有自己独立的组件状态)。
在<ListItem />
组件中,我有一个_handleOnClick
function。 当_handleOnClick
function 被触发时,检查组件 state 显示a: false
和b:true
虽然我看到got here
登录到我的控制台。
我本来希望this.setState({ b: false })
在回调中被调用,并且 state 会更改为a: false
和b:false
。 我错过了什么?
export default class ListItem extends PureComponent {
state = {
a: this.props.a, //this.props.a is true
b: this.props.b, //this.props.b is true
};
_handleOnClick = () => {
this.setState({ a: !this.state.a }, () => {
if (!this.state.a && this.state.b) {
console.log('got here')
this.setState({ b: false })
}
});
};
...
}
你为什么不试试这个
this.setState((prevState, props) => {
//add your stuff here by matching it with previous state
})
为什么要从道具中设置派生的 state ? 我相信将任何内容存储在 state 中被认为是一种反模式,可以在任何时间点从道具中派生。
还有https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html
话虽如此,我相信您的第一个论点应该是完整的 state object。 传递对象或集合状态中的函数之间的差异是什么
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.