简体   繁体   English

推送嵌套对象时反应状态更改

[英]React state changing when pushing nested object

I'm trying to add/push a javascript object (let's call this 'session') to this.state.sessions.我正在尝试向 this.state.sessions 添加/推送一个 javascript 对象(我们称之为“会话”)。

I've tried this two ways:我试过这两种方式:
1) Concat'ing the new session 1) 连接新会话

this.setState({sessions: this.state.sessions.concat(session)});

2) Using React's immutability helpers 2) 使用 React 的 immutability helpers

var newState = React.addons.update(this.state, {
            sessions : {
                $push : [session]
            }
        });
this.setState(newState);

While the shallow data (eg sessions[i].location ) is added correctly, the problem is that all prior session's scope is now set to the new session.scope.虽然浅层数据(例如sessions[i].location )被正确添加,问题是所有先前会话的范围现在都设置为新的 session.scope。 In the picture link below you can see that the first session's scope values ( sessions[0].scope ) were overwritten by the second session's scope values ( sessions[1].scope ).在下面的图片链接中,您可以看到第一个会话的范围值 ( sessions[0].scope ) 被第二个会话的范围值 ( sessions[1].scope ) sessions[1].scope How do I ensure that when I add a new session, prior session's values aren't affected?如何确保在添加新会话时不影响先前会话的值?

App state picture应用状态图

Since sessions is an array, I would've done the following:由于sessions是一个数组,我会做以下事情:

addSession = (newSession) => {
  let tempArray = this.state.sessions.slice();
  tempArray.push(newSession);
  this.setState({sessions: tempArray});
}

The above creates a shallow copy of the sessions array and puts it in a temporary variable.上面创建了一个sessions数组的浅拷贝并将它放在一个临时变量中。 Next, it pushes the new session into the array and once that's done we overwrite the this.state.sessions with the new variable.接下来,它将新会话推送到数组中,一旦完成,我们用新变量覆盖this.state.sessions

I think this has little to do with react, and the problem might be that the object in sessions[0].scope is copied by reference.我认为这与 react 关系不大,问题可能是sessions[0].scope中的对象是通过引用复制的。 That scope object might be reference shared between the old and new session values.scope对象可能是旧会话值和新会话值之间共享的引用。

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

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