[英]How to avoid mutating local state in React in the right and performant way
I´m new in React and I´m trying to learn more about state immutability. 我是React的新手,我试图了解有关状态不变性的更多信息。 The shape of my state property is an object which can have one or several properties holding an array of objects.
我的state属性的形状是一个对象,可以具有一个或多个保存对象数组的属性。
I created a handler in my class for when the user clicks on the div. 我在类中为用户单击div时创建了一个处理程序。
clickDivHandler = (stateProperty, id) => {
let newArray = [...this.state[stateProperty]];
let selectedObject = newArray.filter(element => element.id === id)[0];
selectedObject['new property'] = 'value for new property';
newArray = newArray.filter(element => element.id !== id);
console.log([...newArray, selectedObject]);
}
Basically when the user clicks on the div, the function passes the stateProperty (which holds and array of objects) and the id of that object. 基本上,当用户单击div时,该函数将传递stateProperty(包含对象和对象数组)和该对象的ID。
Then I created a new array for that property to avoid mutating the original one. 然后,我为该属性创建了一个新数组,以避免变异原始数组。
Then I filter out the object with that particular id from the array 然后我从数组中过滤出具有特定ID的对象
Then I create a new property in the object assigned to selectedObject 然后,我在分配给selectedObject的对象中创建一个新属性
Then I remove from the new array the object with that id 然后我从新数组中删除具有该ID的对象
Then I log a new array containing the other objects and the new one. 然后,我记录一个包含其他对象和新对象的新数组。
I´m new and I dont know if this is the right way or if Im mutating or committing any mistake. 我是新手,我不知道这是正确的方法,还是Im变异或犯了任何错误。
I will appreciate any advice. 我将不胜感激任何建议。
You mutated selectedObject
here selectedObject['new property'] = 'value for new property';
您在这里对
selectedObject['new property'] = 'value for new property';
变异selectedObject
selectedObject['new property'] = 'value for new property';
To fix that you would need to do something like this: console.log([...newArray, { ...selectedObject }]);
要解决此问题,您需要执行以下操作:
console.log([...newArray, { ...selectedObject }]);
Some things I would suggest improving: 我建议改善一些方面:
div
is not a clickable element semantically. div
在语义上不是可点击的元素。 react should complain about that in console. redux
redux
reduce
fn in your use case. reduce
fn。 // rough example
this.state[stateProperty].reduce((acc, el) => {
if (el.id === id) {
acc.push({ ...el, new: 'value for new property' })
} else {
acc.push(el);
}
return acc;
}, [])
Explore these libs: 探索以下库:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.