javascript-反应-状态未更新

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

});
martins asked 2020-07-30T19:08:45Z
3个解决方案
114 votes

从reactjs文档中:

setState()不会立即使setState发生突变,但会创建待处理的状态转换。 调用此方法后访问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 ...
    }
)
Anthony Blackshaw answered 2020-07-30T19:09:58Z
2 votes

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

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);
    }
});
deowk answered 2020-07-30T19:10:40Z
2 votes

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

 this.setState( { autocomplete_from: 'event.target.value' }, () => { 
    console.log(this.state.autocomplete_from);//this will print the updated state value
 });
Hemadri Dasari answered 2020-07-30T19:10:59Z
translate from https://stackoverflow.com:/questions/29490581/react-state-not-updated