javascript - Change List of objects in position using map for Reactjs
问题描述
I would like to know how to change the item 'check' to true from position 5 on my array list.
const optionsConsultation = [
{ label: "Maçã", check: false, id: 0, disable: false },
{ label: "Banana", check: false, id: 1, disable: false },
{ label: "Pera", check: false, id: 2, disable: false },
{ label: "Uva", check: false, id: 3, disable: false },
{ label: "Morango", check: false, id: 5, disable: false},
{ label: "Laranja", check: false, id: 6, disable: false }
];
export default () => {
const [datas, setDatas] = useState(optionsConsultation);
useEffect(() =>{
const resetData = datas.map(checks => checks)
)
解决方案
更改嵌套对象/数组中的值可能非常乏味。
如果在您的应用程序中您经常这样做,我建议您尝试使用 Immer ( https://github.com/immerjs/use-immer )。
否则这样做很好:
//
const targetItemIndex = 5;
const resetData = [
...datas.slice(0, targetItemIndex),
{ ...datas[targetItemIndex], check: true },
...datas.slice(targetItemIndex + 1)
];
//
或像这样:
const targetItemIndex = 5;
const resetData = datas.map((item, index) => {
if (index === targetItemIndex) {
return { ...item, check: true };
}
return item;
});
推荐阅读
- twine-game-engine - Sugarcube 使随机图像出现
- python - 在 pyomo 中创建具有稀疏索引的变量
- java - Java应用程序:连接到私人比特币节点的问题
- c# - 将枚举添加到特定类 c# 的列表中
- javafx - 类,groovy FX和调用self
- xcode - IONIC 1 是否支持 iOS12?
- java - Liferay 最佳实践如何制作视图模型/图层以及如何使用 liferay-search-container 显示 2 个表记录
- git - 我在 Visual Studio 应用程序中更改了 2-3 行,现在版本控制说应用程序中的每个文件都是新文件?
- python - 在没有明确声明的情况下禁用 Django ModelForm 字段
- sql-server - 删除没有事件数据的行