无法在组件中设置状态

时间:2016-11-22 04:28:54

标签: reactjs

当发生click事件时,状态不会设置为CompOne中给出的值。它仍然显示初始状态和控制台记录旧状态,即#34;你好"。

var CompOne = React.createClass({

  getInitialState: function() {
    return {
      edit: "hello"
    } 
  },

  editme: function () {
   this.setState({
     edit: "there"
   })
   console.log(this.state.edit)  
 },

  render: function(){
    return (
      <div>
        {this.props.name}
        <button onClick={this.editme}>Edit</button>
      </div>
    )
  }
})


var Pri = React.createClass({
  render: function () {
    return (
      <div>
        < CompOne name = "Anne"/>
        < CompOne name = "Bob"/>
      </div>
    );
  }
})

ReactDOM.render( <Pri /> , document.getElementById("root"));

2 个答案:

答案 0 :(得分:2)

函数setState不同步。以下是React documentation;

中有关此内容的说明
  

setState()不会立即改变this.state但会创建一个   待定状态转换。在调用此文件后访问this.state   方法可以返回现有值。没有   保证调用setState和调用的同步操作   可能会因性能提升而受到批评。

从人的角度来说,这意味着如果你打电话给setState并尝试立即阅读状态,状态可以改变,也可以是相同的。

您可以使用的解决方案是将回调传递给setState方法作为第二个参数:

editme: function () {
   this.setState({
     edit: "there"
   }, function(){
       // this function would be invoked only when the state is changed
       console.log(this.state.edit);
   });
}

第二个参数的目的在同一文档文章中描述:

  

第二个参数是可选的回调函数   完成setState并且组件完成后执行   重新渲染。

答案 1 :(得分:1)

您需要在setState中使用回调函数,因为setState需要时间进行变异,并且在状态发生变异之前执行console.log,因为语句是异步执行的。

   editme: function () {
       this.setState({
         edit: "there"
       }, function(){

       console.log(this.state.edit) 
       }) 
     },

    var CompOne = React.createClass({
    
      getInitialState: function() {
        return {
          edit: "hello"
        } 
      },
    
      editme: function () {
       this.setState({
         edit: "there"
       }, function(){
         
       console.log(this.state.edit) 
       }) 
     },
    
      render: function(){
        return (
          <div>
            {this.props.name}
            <button onClick={this.editme}>Edit</button>
          </div>
        )
      }
    })
    
    
    var Pri = React.createClass({
      render: function () {
        return (
          <div>
            < CompOne name = "Anne"/>
            < CompOne name = "Bob"/>
          </div>
        );
      }
    })
    
    ReactDOM.render( <Pri /> , document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>
<div id="root"></div>