简体   繁体   中英

Select in react does not reflect the state changes

Something weird is happening when I try to us select in reactjs. Here is my code:

onDropDownChange=(e)=>{
    let val = this.props.contactUsReducer.contactUsList.filter(function(item) {
        return item.topic == e.target.value
    });
    let key= e.target.value;
    let name= e.target.name;
    console.log("key "+key+"  val: "+val[0].displayName+" name:"+name);
    this.setState(prevState => {
        return ( {...prevState, [name]:key, displayName: val[0].displayName})
    }, function () {
        console.log(this.state);
    });
}

and in my render I have

<select type="select" className="text-input flex-row-right-item" onChange={this.onDropDownChange} name="topic" value={this.state.displayName}>
  {this.createSelectItems(this.props.contactUsReducer.contactUsList)}
</select>

Also here is my helper function:

createSelectItems=(itemsList)=> {
    let items = [];

    for (let i = 0; i < itemsList.length; i++) {
            items.push(<option key={itemsList[i].topic} value={itemsList[i].topic}>{itemsList[i].displayName}</option>);

    }
    return items;
}

Now when I try to change the select box nothing will change in the UI so select box does not show the updated selection but I clearly see in the state that the state has been updated. Why the changes does not get reflected in select box.

Any idea?

For some reason you are supplying a function to your setState function. I personally find making a copy of the state and setting the properties to work better.

onDropDownChange = e => {
  let val = this.state.myArr.filter(function(item) {
    return item.topic === e.target.value;
  });
  let key = e.target.value;
  let name = e.target.name;
  console.log(
  "key " + key + "  val: " + val[0].displayName + " name:" + name
  );

  let prevState = { ...this.state };
  prevState[name] = key;
  prevState["displayName"] = val[0].displayName;

  this.setState({ ...this.state, prevState });
  console.log(this.state);
};

The value on the select should be one of the values on the options tags, but as values on those options you're mapping the topic but you made value={this.state.displayName} on the select tag ? if you replace it with value={this.state.topic} it will work since it uses the same data mapping. here is a codesandbox exp.

Change value set to displayName in your setState as,

this.setState(prevState => {
        return ( {...prevState, [name]:key, displayName: key})
    }, function () {
        console.log(this.state);
    });

Because the value prop should have the value of the selected option

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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