我想将状态设置为嵌套对象,我尝试了 this answer ,但我不知道每次我setState
按照答案,状态仍然没有设置
这是我尝试过的代码:
// declare the state
constructor(props){
super(props);
this.state = {
bius: {name:'bius', time:0, status:false},
}
}
// Function to setstate
_timer(name){
// this.setState({[name]: !this.state.name})
var upd = {...this.state[name]}
upd.status = !upd.status
console.log(upd.status)
console.log(this.state.bius)
this.setState({upd})
console.log("setstate upd")
console.log(upd)
console.log(this.state.bius)
}
// here I call the function to set state
<TouchableOpacity onPress={()=>{this._timer('bius')}}>
<Text style={[global.global.SubHeaderText, {color:'white'}]}>Start</Text>
</TouchableOpacity>
这是日志的输出:
I/ReactNativeJS(6694): true
I/ReactNativeJS(6694): { name: 'bius', time: 0, status: false }
I/ReactNativeJS(6694): setstate upd
I/ReactNativeJS(6694): { name: 'bius', time: 0, status: true }
I/ReactNativeJS(6694): { name: 'bius', time: 0, status: false }
我不知道为什么 upd.status
已经 true
,但 this.state.bius.status
仍然假
?
为什么this.state.bius.status
没有设置为true
?
最佳答案
您需要绑定(bind)事件。阅读 this react documentation
您还需要使用spread operator在这里也只更改您想要的 key
this._timer.bind(this,'bius');
//..
this.setState(prevState => ({
bius: {
...prevState.bius,
status: !prevState.bius.status
}));
此外,您 upd.status = !upd.status;
将无法工作,因为状态尚未更改。您还需要在那里调用 setState。关于您的问题的评论中提到的另一件事。如果您不打算绑定(bind)事件处理程序,则应该使用箭头函数。
关于javascript - React Native - 设置状态嵌套对象无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49933530/