【问题标题】:React - State not updatedReact - 状态未更新
【发布时间】:2015-06-11 23:46:11
【问题描述】:

在这里我尝试将state.autocomplete 设置为'hello',然后打印它,但状态似乎为空。当我刚刚使用setState 更新状态时,怎么会这样? data 设置为全局变量。

  var data = {
    populate_at: ['web_start', 'web_end'],
    autocomplete_from: ['customer_name', 'customer_address']
  };


  var AutocompleteFromCheckboxes = React.createClass({
    handleChange: function(e) {
      this.setState( { autocomplete_from: 'event.target.value' } );
      console.log('autocompleteFrom state: ', this.state.autocomplete_from);
      // ^  => Uncaught TypeError: Cannot read property 'autocomplete_from' of null
      return 1;
    },
    render: function() {
      var autocompleteFrom = this.props.autocomplete_from.map(function(value) {
        return (
          <label for={value}>
            <input type="checkbox" name={value} value="{value}"
              onChange={this.handleChange.bind(this)}
              ref="autocomplete-from"/>
            {value}
          </label>
        );
      }, this);
      return (
        <div className="autocomplete-from">
          {autocompleteFrom}
        </div>
      );
    }
  });

  var DynamicForm = React.createClass({
    getInitialState: function() {
      return {
        name              : null,
        populate_at       : null,
        same_as           : null,
        autocomplete_from : "not set",
        title             : null
      };
    },
    saveAndContinue: function(e) {
      e.preventDefault();
      var data = {
        name     : this.refs.name.getDOMNode().value,
      };
      console.log('data: ' + data.name);
    },

    render: function() {
      return (
          <AutocompleteFromCheckboxes
            autocomplete_from={this.props.data.autocomplete_from} />
      );
    }
  });


  var mountpoint = document.getElementById('dynamic-form');
  if ( mountpoint ) {
    React.render(<DynamicForm data={data} />, mountpoint);
  }

});

【问题讨论】:

  • @zvona,添加.bind(this) 导致此警告Warning: bind(): You are binding a component method to the component. React does this for you automatically in a high-performance way, so you can safely remove this call. See AutocompleteFromCheckboxes dynamic-form.js?body=1:13 populateAtCheckbox
  • 是的,我注意到了。我的错误:/.

标签: javascript reactjs


【解决方案1】:

来自 reactjs 文档:

setState() 不会立即改变this.state,而是创建一个挂起的状态转换。调用此方法后访问this.state 可能会返回现有值。

https://facebook.github.io/react/docs/component-api.html

您可以做的是向setState 传递一个回调函数,该函数在状态更新后触发:

this.setState(
    {autocomplete_from: ...}, 
    function () {
        ... at this point the state of the component is set ...
    }
)

【讨论】:

【解决方案2】:

您需要设置组件的初始状态,尝试在组件顶部添加以下内容。

getInitialState: function() {
  return {
   autocomplete_from: ''
  };
}

编辑:

在您的 DynamicFrom 组件中,您有:

render: function() {
  return (
      <AutocompleteFromCheckboxes
        autocomplete_from={this.props.data.autocomplete_from} />
  );
}

既然你试图引用你应该写的状态

autocomplete_form={this.state.autocomplete_from}

您还试图从子组件设置状态,它不应该直接修改状态。解决此问题的最佳方法是将函数从 DynamicFrom(保持状态)传递给 AutocompleteFromCheckboxes。像这样。

var DynamicForm = React.createClass({
    handleChange: function(value) {
       this.setState({autocompelete_from: value});
    },
    render: function() {
       return(
          <AutocompleteFromCheckboxes 
            autocomplete_from={this.state.autocomplete_from}
            handleChange={this.handleChange} 
          />
       );
    },
    ....
});

然后在您的子组件中调用该函数

AutocompleteFromCheckboxes = React.createClass({
    ....
    onChange={this.handleChange}
    ....
    handleChange: function(e) {
     this.props.handleChange(e.target.value);
    }
});

【讨论】:

  • 抱歉,我的原始帖子中没有包含 getInitialState。现在更新了帖子以包含更多代码。
【解决方案3】:

要在执行 setState 后查看更新的状态值,您应该执行以下操作

 this.setState( { autocomplete_from: 'event.target.value' }, () => { 
    console.log(this.state.autocomplete_from);//this will print the updated state value
 });

【讨论】:

    猜你喜欢
    • 2019-08-08
    • 2019-05-30
    • 2021-07-30
    • 2020-10-26
    • 2016-10-31
    • 2021-03-22
    • 2021-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多