在 ReactJS 中更新数组中的对象的最佳方法是什么? [英] Whats the best way to update an object in an array in ReactJS?

查看:50
本文介绍了在 ReactJS 中更新数组中的对象的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您有一个数组作为状态的一部分,并且该数组包含对象,那么通过更改其中一个对象来更新状态的简单方法是什么?

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?

示例,修改自关于 react 的教程:

Example, modified from the tutorial on react:

var CommentBox = React.createClass({
  getInitialState: function() {
    return {data: [
      { id: 1, author: "john", text: "foo" },
      { id: 2, author: "bob", text: "bar" }
    ]};
  },
  handleCommentEdit: function(id, text) {
    var existingComment = this.state.data.filter({ function(c) { c.id == id; }).first();
    var updatedComments = ??; // not sure how to do this  

    this.setState({data: updatedComments});
  }
}

推荐答案

在更新状态时,关键部分是将其视为不可变的.如果您能保证,任何解决方案都可以正常工作.

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.

这是我使用 immutability-helper 的解决方案:

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:

这篇关于在 ReactJS 中更新数组中的对象的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆