【发布时间】:2021-12-05 03:08:40
【问题描述】:
什么是更改对象数组的最佳且简洁的方法?
我有一个看起来像这样的代码。
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() with Object
这篇文章支持 3rd 方库和/或深度复制,我怀疑这也不是“正确”的做法。
Whats the best way to update an object in an array in ReactJS?
这个线程还支持很多深拷贝和映射,我想我不需要(它是一个数组,我应该能够通过索引来寻址我的对象)?
How do I update states `onChange` in an array of object in React Hooks
另一个深拷贝解决方案
https://codereview.stackexchange.com/questions/249405/react-hooks-update-array-of-object
名单还在继续……
基本上我想要没有多余行的结果,
如果可能的话:
- 无需深度复制状态以重新注入。
- 没有第 3 方库。
- 不使用键控对象。
- 没有在 set_post 中运行 map/filter 循环。
编辑: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(),无论你对回调做什么,都完全独立于你的get_post.map()回调执行
标签: javascript reactjs object use-state