react-select drop down choices not storing correctly

落爺英雄遲暮 提交于 2019-12-13 05:17:25

问题


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:


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



来源:https://stackoverflow.com/questions/53266666/react-select-drop-down-choices-not-storing-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!