简体   繁体   English

如何在 React 中的对象之间复制嵌套状态

[英]How to copy nested state between objects in React

In a react app, I have state that looks like this:在反应应用程序中,我的状态如下所示:

dates: {"2015-11-20":{
                      "13:00":{...},
                      "14:00":{...}},
        "2015-11-21":{
                      "18:00":{...},
                      "19:00":{...}}}

I'm running into a problem with updating state - my use case is I want users to be able to copy all the times (eg 1pm & 2pm above) to other dates via the UI and have state update accordingly.我遇到了更新状态的问题 - 我的用例是我希望用户能够通过 UI 将所有时间(例如上面的下午 1 点和下午 2 点)复制到其他日期,并相应地更新状态。

So far, all my attempts result in referencing, where the separate objects become linked and any update to one results in an update to the other.到目前为止,我所有的尝试都会导致引用,其中单独的对象链接在一起,对一个对象的任何更新都会导致对另一个对象的更新。

Sample code that produces the broken behaviour:产生破坏行为的示例代码:

copyTimes: function() {
      var keys = [];
      Object.keys(this.state.dates).map(function(key) {
          keys.push(key);
      });

      for(var i in keys) {
        this.state.dates[keys[i]] = this.state.dates[this.state.selectedDate];
      }

      this.setState({dates: this.state.dates});
  }

I believe I might need to use the react add on 'update' to solve this, as per https://facebook.github.io/react/docs/update.html我相信我可能需要根据https://facebook.github.io/react/docs/update.html使用 react add on 'update' 来解决这个问题

but I can't fully understand the syntax approach I need to take.但我不能完全理解我需要采用的语法方法。 How do I cause a correct update to 'copy' the contents of one date: '2015-11-20' to another eg 2015-11-21 in the above example?如何正确更新将一个日期的内容“复制”:“2015-11-20”到另一个日期,例如上例中的 2015-11-21?

EDIT As per (pointed out in comments): What is the most efficient way to deep clone an object in JavaScript?编辑根据(在评论中指出): 在 JavaScript 中深度克隆对象的最有效方法是什么?

  copyTimes: function() {
      var keys = [];
      var tempStart =  JSON.parse(JSON.stringify(this.state.dates));
      Object.keys(this.state.dates).map(function(key) {
          keys.push(key);
      });

      for(var i in keys) {
        tempStart[keys[i]] = JSON.parse(JSON.stringify(this.state.dates[this.state.selectedDate]));
      }

      this.setState({dates: tempStart});
  },

The above works - but is extremely ugly.以上工作 - 但非常丑陋。 Is there a better approach?有没有更好的方法?

 copyTimes: function() { var keys = []; Object.keys(this.state.dates).map(function(key) { keys.push(key); }); var newDates = Object.assign({}, this.state.dates);; for(var i in keys) { newDates[keys[i]] = this.state.dates[this.state.selectedDate]; } this.setState({dates: newDates}); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM