简体   繁体   中英

How to update nested array (multi react-select)

I'm creating an app where I need to store selected values in array nested in object (category below). State looks like:

state = {
    data: {
        user: "",
        title: "",
        text: "",
        category: [], // should store values
    },
    updateNoteId: null,
}

In my render() I have following form:

<form onSubmit={this.submitNote}>
    <Select
        name="category"
        value={this.state.data.category}
        options={options}
        onChange={this.handleMultiChange}
        multi
    />
    <input type="submit" value="Save" />
</form>

Options are:

const options = [
    { value: 1, label: 'one' },
    { value: 2, label: 'two' },
    { value: 3, label: 'three' }
]

So the question is how this.handleMultiChange function should looks like to work. Category[] need to keep all values selected in Select which is react-select component (eg. it should be category = [1,3], when 'one' and 'three' were chosen). I tried many combination but none of them worked so far. I prefer to use ES6 without any external libraries/helpers to do that.

handleMultiChange(selectedOptions) {
  this.setState({ 
    data: {
      ...this.state.data, 
      categories: selectedOptions
    }
  })
}

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