反应更新一系列对象的单个对象 - 映射与整个数组
我有一个在本地状态中具有一系列对象的组件:
const [myState, setState] = useState<SomeObjectType[]>([]);
我可以通过制作整个数组的副本,然后更新我希望更新的单个对象的属性来更新该数组中的一个对象:
option 1 < /strong>
const state = [...myState];
state[id].description = description;
setState(state);
或我可以使用地图:
选项2
const newState = talkingPoints.map(el => {
//
I have a component with an array of objects in local state:
const [myState, setState] = useState<SomeObjectType[]>([]);
I can update a single object in that array by making a copy of the entire array and then update the property of the single object I wish to update:
OPTION 1
const state = [...myState];
state[id].description = description;
setState(state);
Or I can use map:
OPTION 2
const newState = talkingPoints.map(el => {
// ????️ if id equals, update description property
if (el.id === id) {
return {...el, description};
}
// ????️ otherwise return as is
return el;
});
setData(newState);
Or can I do this (since I am 100% certain the id exists in the array)?
OPTION 3
const handleUpdate = () => {
setState(prevState => ({
...prevState,
prevState[id].description = description
}))
}
For cases where I am not 100% certain I can use map and find it:
OPTION 4
const handleUpdate = () => {
setState(prevState => ({
myState: prevState.myState.map(el => el.id === id ? { ...el, description } : el)
}))
}
What is recommended/best practice?
Is Option 1 (fully array copy) faster than using map?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
选项3和OPNTION 4是不正确的,Prevstate/Mystate是一个数组,您正在返回对象,这肯定会导致打字稿中的错误。对于选项1和2,它们仅在声明性和不设计方法之间有所不同。声明性编程制造了更可读的代码。
在选项1:
在带有
MAP
函数的选项2上,它可以写如下:总而言之,使用映射/过滤器更可更新数组。
以下是Sandbox 比较选项1和2
Option 3 and opntion 4 are incorrect, the prevState/myState is an array and you are returning an object, this will surely cause error in typescript. As to option 1 and 2, they only differ between declaritive and imperitive way of programming. And declaritive programming makes more readable code.
On option 1:
On option 2 with
map
function, it can be written as follows:In conclusion, use map/filter is more preferable to update array.
Here's sandbox to compare option 1 and 2