import Select, { components } from "react-select";
...
handleBookKeyWordDropDown (key_wor) {
let keys;
if (key_wor !== null) {
keys = key_wor;
} else {
keys = []
};
this.setState({
currentBook:{
key_words: keys
}
});
}
handleBookBBKDropDown (bbks) {
let bks;
if (bbks !== null) {
bks = bbks;
} else {
bks = []
};
this.setState({
currentBook:{
bbk: bks
}
});
}
...
<div className="row justify-content-end">
<div className="col-4">
<label>Ключевые слова:</label>
</div>
<div className="col-8">
<Select
closeMenuOnSelect={false}
options={this.state.key_words}
value={this.state.currentBook.key_words}
getOptionLabel={ x => x.name}
getOptionValue={ x => x.id}
onChange={this.handleBookKeyWordDropDown}
isMulti
isSearchable
placeholder="Выберите ключевые слова"
/>
</div>
<div className="row justify-content-end">
<div className="col-4">
<label>ББК:</label>
</div>
<div className="col-8">
<Select
closeMenuOnSelect={false}
options={this.state.bbk}
value={this.state.currentBook.bbk}
getOptionLabel={ x => (x.code+' '+x.description)}
getOptionValue={ x => x.id}
onChange={this.handleBookBBKDropDown}
isMulti
isSearchable
placeholder="Выберите ББК"
/>
</div>
</div>
</div>
So the logic is: initially every one of them has its own default value, which should be changed while changing selected values.
Issue appears when I change anything in any of Select: if I remove any selected value from any Select, other Select's selected values are being removed. But after that if I add something to anything or remove, everything works fine.
Have no idea how to deal with it, possibly because of lack of experience with React.
Looking for some help, guys: :)
You have currentBook
as an object which store the value of both select fields and onChange
you are creating a new object with single select value overriding the second select value
Change your code to this
handleBookBBKDropDown (bbks) {
let bks;
if (bbks !== null) {
bks = bbks;
} else {
bks = []
};
this.setState({
currentBook:{
...this.state.currentBook, bbk: bks
}
});
}
handleBookKeyWordDropDown (key_wor) {
let keys;
if (key_wor !== null) {
keys = key_wor;
} else {
keys = []
};
this.setState({
currentBook:{...this.state.currentBook,
key_words: keys
}
});
}
Here, I am using to Spread operator to use previous currentBook
object and overriding only changed select value
The problem is that you are overriding the state values of other dropdown. You have to keep other state value in current state.
First declare your state like this:
this.state = {currentBook:{bbk:[],key_words:[]}}
Then do this:
// handleBookKeyWordDropDown
this.setState({currentBook:{
...this.state.currentBook,
key_words: keys
}
});
// handleBookBBKDropDown
this.setState({currentBook:{
...this.state.currentBook
bbk: bks
}
});
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.