[英]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 > TL;DR:调用 this.setState 来更新数组避免了 < select > label 与选定的 < option >
Explanations: I am building an array of options like that (dd is for drop down):说明:我正在构建一个这样的选项数组(dd 用于下拉):
let ddUsers = (this.state.users.map(user => <option key={uuid.v4()} value={user.key}>{user.name}</option>))
Then here is my select:然后这是我的 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这是我的 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.现在使用注释的最后一行,select 的 label 正确更新为所选选项。 But when I uncomment this line, the function is called, this.state.selected is updated BUT the select is blocked on the 1st option.但是当我取消注释这一行时,调用了 function,this.state.selected 已更新,但select 在第一个选项上被阻止
Is that clear?明白了吗? What am I missing?我错过了什么?
In fact: just calling setState in the function avoid the correct change实际上:只需在 function 中调用 setState 即可避免正确更改
This is because you are setting the key
of option
to dynamic value which gets updated every time.这是因为您将option
的key
设置为每次更新的动态值。 Try to use a know and unique one as the key
.尝试使用一个知道和独特的作为key
。 Code such as below如下代码
<option key={user.key} value={user.key}>
This ensures, you have unique key and also is predictable.这可以确保您拥有唯一的密钥并且是可预测的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.