小编典典

反应-状态未更新

reactjs

在这里,我尝试设置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);
  }

});

阅读 232

收藏
2020-07-22

共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 ...
    }
)
2020-07-22