繁体   English   中英

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

[英]React Native - set State nested object doesn't work properly

我想将状态设置为嵌套对象,然后尝试了此答案 ,但我不知道每次我回答答案后的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>

这是log的输出:

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仍然为false

为什么this.state.bius.status未设置为true

您需要绑定事件。 阅读此反应文档

您还需要在此处使用扩展运算符 ,并且也只需更改所需的密钥

this._timer.bind(this,'bius');
//..

this.setState(prevState => ({ 
   bius: {
      ...prevState.bius,
      status: !prevState.bius.status
}));

您也upd.status = !upd.status; 由于状态没有改变,因此无法使用。 您也需要在那里调用setState。 关于您的问题的评论中提到的另一件事。 如果不打算绑定事件处理程序,则应使用箭头函数。

setState是异步函数。 因此,如果要打印状态,则应在回调时使用console.log()。 例如:

this.setState({bius: {name:'example'}},()=>{console.log(this.state)})
this.setState() updates the state  asynchronously. That is why you do not see in console log. To get the log correctly add a console.log in render function as below .

export default class app extends Component {
  constructor(props) {
    super(props);
    this.state = {
      bius: { name: 'bius', time: 0, status: false },
    }
  }

  // Function to setstate
  _timer(name) {
    var upd = { ...this.state[name] }
    upd.status = !upd.status
    this.setState({ bius: upd })
  }


  render() {
    console.log("MYLOG", this.state.bius)
    return (
      <TouchableOpacity style={{ margin: 100 }} onPress={() => { this._timer('bius') }}>
        <Text >Start</Text>
      </TouchableOpacity>
    )
  }
}

我认为您必须误解this.setState({upd})

您可以使用另一种方式this.setState({bius:upd})试试这个,让我知道发生了什么。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM