React - State未正确更新

时间:2018-04-15 22:12:11

标签: javascript reactjs

我正在使用<Select>组件,这是创建下拉菜单的Material-ui组件之一。我想要做的是将更新后的状态传递给<Select>组件。

我将组件的value属性设置为"value={ this.state.dropDownField }"

我还将<Select>组件的onChange属性设置为"onChange={ this.handleDropdownFieldChange.bind(this) }"

因此,当选择下拉菜单中的菜单时,将启动handleDropdownFieldChange功能并将状态更新为this.setState({ dropDownField: event.target.value })

但是,更新后的状态未正确传递回<Select>组件。

有人可以帮我解决这个问题吗?

这是我的代码:

&#13;
&#13;
class NewsContainer extends React.Component {
  state = {
    dropDownField: ''
  };

  handleDropdownFieldChange = (event) => {
    this.setState({ dropDownField: event.target.value });
    console.log("This is inside the handleDropdownFieldChange");
    console.log(this.dropDownField);
  }

  displayDropDowns() {
    return (
      <div>
        <form>
          <DialogContent>
            <div>
              <h3>Advanced Search</h3>
            </div>

            <h2>Filter results by</h2>

            <div className="advanced-search-body">
              <div className="advanced-search-drop-down">
                <InputLabel>Select Category</InputLabel>
                <Select
                  value={ this.state.dropDownField }
                  fullWidth
                  onChange={ this.handleDropdownFieldChange.bind(this) }
                >
                  <MenuItem value="Technology">Technology</MenuItem>
                  <MenuItem value="Business">Business</MenuItem>
                  <MenuItem value="Finance">Finance</MenuItem>
                  <MenuItem value="Startups">Startups</MenuItem>
                  <MenuItem value="Investment">Investment</MenuItem>
                  <MenuItem value="Stocks">Stocks</MenuItem>
                  <MenuItem value="Apps">Apps</MenuItem>
                </Select>
              </div>
            </div>
          </DialogContent>
        </form>
      </div>
    );
  }

  render() {

    return (
      <div>
        <div>
          <h3>Top Headlines</h3>

          {this.displayDropDowns()}
        
        </div>
      </div>
    );
  }
}

export default NewsContainer;
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

使用素材UI时,onChange回调的签名与Vanilla HTML / React不同:

  handleDropdownFieldChange = (event, index, value) => {
    this.setState({ dropDownField: value });
    console.log("This is inside the handleDropdownFieldChange");
    console.log(this.dropDownField);
  }