如何在没有参考的情况下复制状态? [英] How can I copy the state in react without reference?

查看:53
本文介绍了如何在没有参考的情况下复制状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我要像这样复制状态时:

When I want to copy the state like this:

let copy = this.state.foo
copy.push('bar')

状态已正确复制,但带有参考,并且当我更改复制"时,主要状态也会更改.

the state copied correctly, but with its reference, and when I change 'copy' the main state changes.

我应该怎么做才能避免这种变化?

What should I do to avoid this change?

推荐答案

您可以使用

You can use array spread or Array.concat() to make a shallow clone, and add new items as well):

const state = {
  foo: ['bar']
};

const copy = [...state.foo, 'bar'];

console.log(copy === state.foo); // false

这篇关于如何在没有参考的情况下复制状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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