Whats the best way to update an object in an array in ReactJS?

前端 未结 4 1247
悲&欢浪女
悲&欢浪女 2020-11-22 10:56

If you have an array as part of your state, and that array contains objects, whats an easy way to update the state with a change to one of those objects?

Example, mo

4条回答
  •  旧时难觅i
    2020-11-22 11:03

    You can do this with multiple way, I am going to show you that I mostly used. When I am working with arrays in react usually I pass a custom attribute with current index value, in the example below I have passed data-index attribute, data- is html 5 convention.

    Ex:

    //handleChange method.
    handleChange(e){
      const {name, value} = e,
            index = e.target.getAttribute('data-index'), //custom attribute value
            updatedObj = Object.assign({}, this.state.arr[i],{[name]: value});
          
      //update state value.
      this.setState({
        arr: [
          ...this.state.arr.slice(0, index),
          updatedObj,
          ...this.state.arr.slice(index + 1)
        ]
      })
      }

提交回复
热议问题