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

前端 未结 4 1246
悲&欢浪女
悲&欢浪女 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条回答
  •  轮回少年
    2020-11-22 11:13

    I quite like doing this with Object.assign rather than the immutability helpers.

    handleCommentEdit: function(id, text) {
        this.setState({
          data: this.state.data.map(el => (el.id === id ? Object.assign({}, el, { text }) : el))
        });
    }
    

    I just think this is much more succinct than splice and doesn't require knowing an index or explicitly handling the not found case.

    If you are feeling all ES2018, you can also do this with spread instead of Object.assign

    this.setState({
      data: this.state.data.map(el => (el.id === id ? {...el, text} : el))
    });
    

提交回复
热议问题