更新深度ReactJS状态 [英] Updating deep ReactJS state

查看:73
本文介绍了更新深度ReactJS状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ReactJS组件状态的项目数组,我正在迭代创建一个表单。我的问题是:当字段更改时,如何最好地更新这些项目?

I have an array of items in a ReactJS component state that I'm iterating over to create a form. My question is: How do I best update those items when the fields change?

例如:

var items = this.state.foo.bar.items.map(function(item, i) {
    return <input value={item.baz} onChange={??}
});

在这种情况下,我的onChange处理程序会是什么样子?我是否直接更改 item.baz 属性,然后 this.setState(state)?似乎错了。我正在查看 React immutability helpers ,但是看看如何使用数组索引。

What would my onChange handler look like in this case? Do I change the item.baz property directly, then this.setState(state)? Seems wrong. I'm looking at the React immutability helpers, but see how to work with array indexes.

谢谢。

推荐答案

您可以使用索引更新正确的数组项将其传递给 onChange 通过 bind 然后动态构建对象以传递给 update

You could use the index to update the correct array item by passing it to onChange via bind and then dynamically building the object to pass to update:

var Hello = React.createClass({
    getInitialState : function() {
      return  {
        foo : {
          bar : {
            items : [ { baz : 1 }, { baz : 2 }, { baz : 3 } ]
          }
        }
      };
    },
    onChange : function( idx, item, event ) {
      var objForUpdate = { foo: { bar: { items : {} } } };
      objForUpdate.foo.bar.items[ idx ] = { $set : { baz : event.target.value } };
      var newData = React.addons.update( this.state, objForUpdate );
      this.setState( newData );
    },
    render: function() {
      var _this = this;
      var items = this.state.foo.bar.items.map(function(item, i) {
        return <input value={item.baz} onChange={_this.onChange.bind( _this, i, item )}></input>
      });
      return <div>{items}</div>;
    }
});

我理解这只比

onChange : function( idx, item, event ) {
  item.baz = event.target.value;
  this.setState( this.state );
}

如果要覆盖 shouldComponentUpdate 并且对何时更具选择性每次重新渲染调用this.setState()

jsfiddle

这篇关于更新深度ReactJS状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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