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

标签 javascript reactjs react-native

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

相关文章:

javascript - SVG 过滤器在嵌入 JavaScript 时不起作用

javascript - 如何在同一个闭包中使用多个 grunt 任务?

javascript - onClick 不适用于我的 React 组件

reactjs - Redux-saga 与 Internet Explorer

react-native - 刷新navigator.pop()上的组件

javascript - 如何将用户输入保存到 HTML 和 JavaScript 中的变量中

javascript - 使用 JavaScript 下载图像

javascript - 类型错误 : dropdown is null when trying to access Dom element in reactjs

react-native - 如何在带有弹性框的 native react 中创建圆形

javascript - react-native with react-navigation 和 redux [transfer state across screen]