是否可以映射包含在 useState 中的数组,然后使用 setter 函数更新状态 - 反应清单
Is it possible to map an array contained in useState and then update the state with the setter function - react checklist
我正在尝试创建一个清单组件,我可以在其中将清单项目切换为 true/false,然后在单独的元素中显示此数据。
当我尝试我的示例代码时它抛出这个错误:TypeError: checkList.map is not a function
我也查看了其他挂钩,但没有找到明显的解决方案。
示例代码:
import React, {useState} from 'react';
const CheckListTest = () => {
const [checklist, setChecklist] = useState([
{name: 'option1', value: false},
{name: 'option2', value: false},
]);
return (
<>
{checklist.map((item) => {
return item.value === true ? item.name : '';
})}
{checklist.map((item) => {
return (
<div
onClick={() => {
setChecklist(...checklist, (item.value = !item.value));
}}
>
{item.name}
</div>
);
})}
</>
);
};
UI 示例:
- 当点击底部列表中的项目时,它应该从数组中删除自己并推送到上面的列表。 (还没有走到这一步,因为我仍然卡住了)
提前致谢
您正在使用错误的参数数量调用 setCheckList
函数。 useState
中的 setter 接受一个参数。尝试将 onClick
处理程序中的 setCheckList
函数更改为:
setCheckList(checkList => {
const newCheckList = [...checkList];
// Do someting here to change the `newCheckList` variable, e.g.:
if (!item.value) {
const index = newCheckList.findIndex(item => item.value);
newCheckList.splice(index, 1);
}
return newCheckList;
})
我正在尝试创建一个清单组件,我可以在其中将清单项目切换为 true/false,然后在单独的元素中显示此数据。
当我尝试我的示例代码时它抛出这个错误:TypeError: checkList.map is not a function
我也查看了其他挂钩,但没有找到明显的解决方案。
示例代码:
import React, {useState} from 'react';
const CheckListTest = () => {
const [checklist, setChecklist] = useState([
{name: 'option1', value: false},
{name: 'option2', value: false},
]);
return (
<>
{checklist.map((item) => {
return item.value === true ? item.name : '';
})}
{checklist.map((item) => {
return (
<div
onClick={() => {
setChecklist(...checklist, (item.value = !item.value));
}}
>
{item.name}
</div>
);
})}
</>
);
};
UI 示例:
提前致谢
您正在使用错误的参数数量调用 setCheckList
函数。 useState
中的 setter 接受一个参数。尝试将 onClick
处理程序中的 setCheckList
函数更改为:
setCheckList(checkList => {
const newCheckList = [...checkList];
// Do someting here to change the `newCheckList` variable, e.g.:
if (!item.value) {
const index = newCheckList.findIndex(item => item.value);
newCheckList.splice(index, 1);
}
return newCheckList;
})