简体   繁体   中英

setState with array from onChange of <select> avoid the change of the <select> label

TL;DR: calling this.setState to update an array avoid the change of a < select > label with the selected < option >

Explanations: I am building an array of options like that (dd is for drop down):

let ddUsers = (this.state.users.map(user => <option key={uuid.v4()} value={user.key}>{user.name}</option>))

Then here is my select:

<select onChange={this.handleFilter}>{ddUsers}</select>

This works perfectly: it appears first with the first option and is able to display the others.

Here is my onChange function: handleFilter

handleFilter = (event) => {

    let selectedUsers;

    console.log(event.target.value, this.state.DEFAULT_KEY)
    if (event.target.value === this.state.DEFAULT_KEY) {
        selectedUsers = [...this.state.users];
    } else {
        selectedUsers = (this.state.users.filter(user => user.key === event.target.value));
    }

    // this.setState({selected: selectedUsers}); <-- The problem comes from this line (looks like atleast)

}

Now with the commented last line, the label of the select correctly update to the selected options. But when I uncomment this line, the function is called, this.state.selected is updated BUT the select is blocked on the 1st option.

Is that clear? What am I missing?

In fact: just calling setState in the function avoid the correct change

This is because you are setting the key of option to dynamic value which gets updated every time. Try to use a know and unique one as the key . Code such as below

<option key={user.key} value={user.key}>

This ensures, you have unique key and also is predictable.

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