简体   繁体   English

反应-状态未正确更新

[英]React - State is not updating properly

I am using <Select> component, which is one of the Material-ui components to create drop down menu. 我正在使用<Select>组件,这是创建下拉菜单的Material-ui组件之一。 What I am trying to do is pass the updated state to <Select> component. 我想做的是将更新后的状态传递给<Select>组件。

I set the value property of the component to "value={ this.state.dropDownField }" . 我将组件的value属性设置为"value={ this.state.dropDownField }"

I also set the onChange property of the <Select> component to "onChange={ this.handleDropdownFieldChange.bind(this) }" . 我还将<Select>组件的onChange属性设置为"onChange={ this.handleDropdownFieldChange.bind(this) }"

So when the menu in the dropdown menu has been selected, the handleDropdownFieldChange function will be initiated and update the state to this.setState({ dropDownField: event.target.value }) . 因此,在选择下拉菜单中的菜单后,将启动handleDropdownFieldChange函数并将状态更新为this.setState({ dropDownField: event.target.value })

However, that updated state is not properly passed back to the <Select> component. 但是,该更新状态未正确传递回<Select>组件。

Could anyone please help me with this? 有人可以帮我吗?

Here is my code: 这是我的代码:

 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; 

When using material UI, the onChange callback has a different signature than the Vanilla HTML/React: 使用实质性UI时,onChange回调与Vanilla HTML / React具有不同的签名:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM