[英]React JS setState for an array
I have a data and each data has a state, I put it on React Hooks array state.我有一个数据,每个数据都有一个状态,我把它放在 React Hooks 数组状态上。 This is my current state that I had after requesting data from server
这是我从服务器请求数据后的当前状态
console.log("panduan : ", panduan)
// Output
panduan :
[6] -> [false, false, false, false, false, false]
So each of these boolean are supposed to be a trigger button for this component below.所以这些布尔值中的每一个都应该是下面这个组件的触发按钮。
I have a component and each data should set their own state, this is my component.我有一个组件,每个数据都应该设置自己的状态,这是我的组件。
data.map((post, index) => {
<TriggerButton onClick={() => setPanduan([!panduan[index]])}>
{post.year}
</TriggerButton>
})
// this Child component should be shown when state is true
const content = (
<Triggered show={panduan[index]}>
{post.someData}
</Triggered>
)
this code above is still not working, maybe because I didn't use the setPanduan
on the right way.上面的这段代码仍然不起作用,也许是因为我没有以正确的方式使用
setPanduan
。 So how to setPanduan
for each data?因此,如何
setPanduan
每个数据?
I think you may be looking for something more like this in your Parent onClick method我想你可能在你的父 onClick 方法中寻找更像这样的东西
onClick={() => {
const tempArray = [...panduan];
tempArray[index] = !tempArray[index];
setPanduan(tempArray);
}
as what you currently have would end up changing the entire state to a single item array and remove the data that was initialised there from the server :)因为您目前拥有的最终会将整个状态更改为单个项目数组并从服务器中删除在那里初始化的数据:)
You are not setting the updated array right.您没有正确设置更新的数组。 Make sure to destructure/clone the old array and toggle only the intended index like so:
确保解构/克隆旧数组并仅切换预期索引,如下所示:
data.map((post, index) => {
<TriggerButton onClick={() => {
// clone old state
const newArray = [...panduan];
// update toggled index
newArray[index] = !newArray[index]
setPanduan(newArray)
}>
{post.year}
</TriggerButton>
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.