[英]React state changing when pushing nested object
我正在尝试向 this.state.sessions 添加/推送一个 javascript 对象(我们称之为“会话”)。
我试过这两种方式:
1) 连接新会话
this.setState({sessions: this.state.sessions.concat(session)});
2) 使用 React 的 immutability helpers
var newState = React.addons.update(this.state, {
sessions : {
$push : [session]
}
});
this.setState(newState);
虽然浅层数据(例如sessions[i].location
)被正确添加,问题是所有先前会话的范围现在都设置为新的 session.scope。 在下面的图片链接中,您可以看到第一个会话的范围值 ( sessions[0].scope
) 被第二个会话的范围值 ( sessions[1].scope
) sessions[1].scope
。 如何确保在添加新会话时不影响先前会话的值?
由于sessions
是一个数组,我会做以下事情:
addSession = (newSession) => {
let tempArray = this.state.sessions.slice();
tempArray.push(newSession);
this.setState({sessions: tempArray});
}
上面创建了一个sessions
数组的浅拷贝并将它放在一个临时变量中。 接下来,它将新会话推送到数组中,一旦完成,我们用新变量覆盖this.state.sessions
。
我认为这与 react 关系不大,问题可能是sessions[0].scope
中的对象是通过引用复制的。 该scope
对象可能是旧会话值和新会话值之间共享的引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.