gpt4 book ai didi

javascript - React Native - 设置状态嵌套对象无法正常工作

转载 作者:行者123 更新时间:2023-11-28 14:35:20 24 4
gpt4 key购买 nike

我想将状态设置为嵌套对象,我尝试了 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/

24 4 0
文章推荐: css - Materialize CSS 模态在另一个模态中被裁剪
文章推荐: javascript - 如何在 Facebook 上发布幻灯片?
文章推荐: jquery - 带有 SVG onclick 问题的 HTML
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com