[英]Alter Object Array in React with useState-hook without deep copying
改变对象数组的最佳和干净的方法是什么?
我有一个看起来像这样的代码。
const [get_post, set_post] = useState([
{name: "First"},
{name: "Second"},
{name: "Third"},
])
我想在某个索引上添加和编辑键。 所以我这样做:
<button onClick={()=>
set_post([...get_post, get_post[0].content = "This is index zero" ])
}> Manipulate! </button>
我的结果是这样的:
[
{"name": "First", "content": "This is index zero"},
{"name": "Second"},
{"name": "Third"},
"This is index zero" <-- This line is the problem
]
我在谷歌上搜索了很多,但这似乎是一个常见的主题。
这篇文章用键控对象描述了相同的问题和解决方案,这对我没有帮助。
React Hooks useState() 与 Object
这篇文章支持 3rd 方库和/或深度复制,我怀疑这也不是“正确”的做法。
在 ReactJS 中更新数组中的对象的最佳方法是什么?
这个线程还支持很多深拷贝和映射,我想我不需要(它是一个数组,我应该能够通过索引来寻址我的对象)?
如何在 React Hooks 的对象数组中更新状态`onChange`
另一种深拷贝解决方案
https://codereview.stackexchange.com/questions/249405/react-hooks-update-array-of-object
名单还在继续……
基本上我想要没有多余线条的结果,
如果可能的话:
编辑:为什么在 setPost 中不需要 map 的原因。
在我的特定场景中,呈现 getPost 的模块已经是一个地图循环。 试图避免嵌套循环。
(我的逻辑简化了)
const [get_post, set_post] = useState([
{name: "First"},
{name: "Second"},
{name: "Third"},
])
//Render module
//Fixed numbers of controllers for each Object in Array.
get_post.map((post, index)=> {
<>
<button onClick={()=>
set_post([...get_post, get_post[index].content = "Content 1" ])}
}>
Controller 1
</button>
<button onClick={()=>
set_post([...get_post, get_post[index].content = "Content 2" ])}
}>
Controller 2
</button>
<button onClick={()=>
set_post([...get_post, get_post[index].content = "Content 3" ])}
}>
Controller 3
</button>
//...
</>
})
如果您只想更改第一个属性,请先从数组中提取它。
您可以使用功能更新方法访问当前状态值并返回一个包含您想要的更改的新值。
set_post(([ first, ...others ]) => [{
...first,
content: "This is index zero"
}, ...others])
要更改任何特定索引,您可以将当前数组映射到一个新数组,在到达时为目标索引创建一个新对象
let x = the_target_index
set_post(posts => posts.map((post, i) => i === x ? {
...post,
content: `This is index ${x}`
} : post))
我找到了一个有效的解决方案!
我还没有在其他地方看到过这个帖子,所以研究一下可能很有趣。
要按索引更改或向数组中的对象添加键/值,只需执行以下操作:
<button onClick={() => {
set_modules( [...get_modules , get_modules[index].content = "my content" ] )
set_modules( [...get_modules ] ) //<-- this line removes the last input
}
}>
正如 Phil 所写,较早的代码被解释为:
const val = "This is index zero";
get_post[0].content = val;
get_post.push(val);
这似乎删除了最新的get_post.push(val)
有人可以解释为什么会这样吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.