React.js:setState覆盖,不合并 [英] React.js: setState overwriting, not merging

查看:327
本文介绍了React.js:setState覆盖,不合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对React.JS还是很陌生,我正在通过构建砖石风格的布局进行试验.

I'm quite new to React.JS and I am in the process of experimenting by building a masonry-style layout.

我将每个元素呈现到DOM,然后需要遍历每个项目,并根据前面的元素应用x和y位置.

I render each element to the DOM, then I need to loop over each item and apply x and y positions based on the preceding elements.

初始模型如下:

[
  {
    "title": "The Forrest",
    "description": "some cool text",
    "imgSmallSrc": "/img/img4-small.jpg",
    "imgAlt": "Placeholder image",
    "tags": [
        "Design",
        "Mobile",
        "Responsive"
    ],
    "date": 1367154709885,
    "podStyle": {
      "width": 253
    }
  }
]

(为了使内容简短,我只显示了一项).

(I've only shown one item to keep things short).

完成循环并获取x和y数据后,我要将其应用于podStyle对象.我用以下数据调用setState():

Once I complete the loop and have my x and y data I want to apply this to the podStyle object. I call setState() with the following data:

[
  {
    "podStyle": {
      "x": 0,
      "y": 0,
      "height": 146,
      "width": 253
    }
  }
]

这似乎从模型中删除了所有当前数据,而只剩下了podStyle数据.我是否误解了合并的工作原理?

This seems to remove all current data from the model and leave me with just the podStyle data. Am I misunderstanding how this merge works?

在此先感谢您的帮助!

推荐答案

如果您的状态是一个对象:

If your state is an object:

getInitialState: function() {
  return { x: 0, y: 0 };
}

您可以使用setState在该对象上设置单个键:

you can use setState to set individual keys on that object:

this.setState({ x: 1 }); // y still == 0

React不会智能合并您的状态;例如,这不起作用:

React does no intelligent merging of your state; for example, this does not work:

getInitialState: function() {
  return {
    point: { x: 0, y: 0 },
    radius: 10
  };
}

this.setState({point: {x: 1}});
// state is now == {point: {x: 1}, radius: 10} (point.y is gone)

如@ssorallen所述,您可以使用不变性帮助器来获取您追求的效果:

As mentioned by @ssorallen, you can use the immutability helpers to get the effect you're after:

var newState = React.addons.update(this.state, {
  point: { x: {$set: 10} }
});
this.setState(newState);

有关示例,请参见此JSFiddle : 查看全文

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