英文:
How to STOP React state from being modified when modifying array set to state?
问题
Trust you are having a great day!
I'm running into a serious issue with React. I have a state which holds an array. In a function I copy the state into a new variable. When I modify this newly defined variable it also updates the state which is not what I want.
Example:
const [arrayState, setArrayState] = useState(
[
{
id: 'ID_1',
text: 'item 1',
},
{
id: 'ID_2',
text: 'item 2',
},
{
id: 'ID_3',
text: 'item 3',
},
{
id: 'ID_4',
text: 'item 4',
},
]
);
const myFunction = () => {
let myVariable = [...arrayState];
myVariable[1].text = 'myVariable item 2'; // This is modifying arrayState as well which is wrong
};
I only want myVariable
to be modified and not my state (arrayState
) as well.
英文:
Trust you are having a great day!
I'm running into a serious issue with React. I have a state which holds an array. In a function I copy the state into a new variable. When I modify this newly defined variable it also updates the state which is not what I want.
Example:
const [arrayState, setArrayState] = useState(
[
{
id: 'ID_1'
text: 'item 1',
},
{
id: 'ID_2'
text: 'item 2',
},
{
id: 'ID_3'
text: 'item 3',
},
{
id: 'ID_4'
text: 'item 4',
},
]
);
const myFunction = () => {
let myVariable = [...arrayState];
myVariable[1].text = 'myVariable item 2'; // This is modifying arrayState as well which is wrong
};
I only want myVariable
to be modified and not my state (arrayState
) as well.
答案1
得分: 1
你可以使用 structuredClone
来对对象数组进行深度克隆。
let myVariable = structuredClone(arrayState);
或者,对于这个特定的数据结构,也可以使用以下解决方案:
let myVariable = arrayState.map(o => ({...o}));
英文:
You can use structuredClone
to make a deep clone of the array of objects.
let myVariable = structuredClone(arrayState);
Alternatively, a solution that only works for this specific data structure:
let myVariable = arrayState.map(o => ({...o}));
答案2
得分: 0
这与原始值和引用值有关。数组和对象不存储值,而是引用内存中存储值的地址。一个简单的例子:
const func = () => {
// 相同的内存引用
const temp = arrayState;
temp[1] = "4";
setAttayState(temp);
}
上面的代码不会重新渲染,因为值的引用没有改变。
您必须像这样分配新的引用地址:
const func = () => {
// 创建新的引用
const temp = [...arrayState];
temp[1] = "4";
setAttayState(temp);
}
英文:
It has to do with primitive and reference values. Arrays and objects do not store values, but they refer to addresses in memory where values are stored. A simple example:
const func = () => {
// Same memory reference
const temp = arrayState;
temp[1] = "4";
setAttayState(temp);
}
above code does not re-render because reference of the value has not changed.
You have to assign new reference address like this:
const func = () => {
// Create new reference
const temp = [...arrayState];
temp[1] = "4";
setAttayState(temp);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论