react-select drop down choices not storing correct

2019-08-26 15:17发布

I'm using a react-select drop down to allow users to choose multiple options between A, B and C. Currently this works on the UI but when an option is de-selected, it is not removed from the array. Can anyone give me hints as to how this is done? (Example, A, B, and C are selected, then A is unselected, how can A be removed from the array?)

    var choice = [];
    const choices = [
      {value: 'a', label: 'a'},
      {value: 'b', label: 'b'},
      {value: 'c', label: 'c'},
     ];          

    handleChange = (selectedChoice) => {
    this.setState({ selectedChoice });
    for (var i =0; i < selectedChoice.length; i++) {
       if (choice.indexOf(selectedChoice[i].value) == -1){
       choice.push(selectedChoice[i].value); 
        }
      }
    }

Then, futher down in the code console.log(choice) is called, printing when a button is clicked. Followed by:

render(){
 return (
  <Div ClassName = "box">
   <Select options = {choices}
     isMulti
     value = {this.state.selectedChoice}
     onChange = {this.handleChange}
    /> </Div> );}

Push and pop won't work as the option could be in the middle.

1条回答
可以哭但决不认输i
2楼-- · 2019-08-26 15:51

You don't need another choice variable.you already have selectedChoice state that will store all the selected value for you.

Working Solution: https://codesandbox.io/embed/0pr9yoo8l

查看更多
登录 后发表回答