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

前端 未结 4 1287
悲&欢浪女
悲&欢浪女 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:16

    While updating state the key part is to treat it as if it is immutable. Any solution would work fine if you can guarantee it.

    Here is my solution using immutability-helper:

    jsFiddle:

      var update = require('immutability-helper');
    
      handleCommentEdit: function(id, text) {
        var data = this.state.data;
        var commentIndex = data.findIndex(function(c) { 
            return c.id == id; 
        });
    
        var updatedComment = update(data[commentIndex], {text: {$set: text}}); 
    
        var newData = update(data, {
            $splice: [[commentIndex, 1, updatedComment]]
        });
        this.setState({data: newData});
      },
    

    Following questions about state arrays may also help:

    • Correct modification of state arrays in ReactJS
    • what is the preferred way to mutate a React state?

提交回复
热议问题