[英]React Hooks Update Nested Array
我有一个 object 数组,使用 useState 挂钩在 state 中命名为选项,我只想在特定索引处更新嵌套数组 object。
var subOptionModel = {
text: "test",
price: 0,
};
var optionModel = {
optionSetId: 0,
optionName: "",
optionPrice: 0,
editOptionName: false,
subOptions: [subOptionModel],
};
const [options, setOptions] = useState([optionModel]);
我在选项 state 中有多个选项,我如何更新 state,就像索引 2 处的选项和 1 处的子选项一样,这是我尝试这样做的。
setOptions(
options.map((x, index) => {
if (index !== optionIndex) return x;
x.subOptions.map((subItem, subIndex) => {
console.log(subItem);
if (subIndex !== subOptionIndex) return subItem;
return {
...subItem,
text: text
};
});
}),
);
我建议您使用不可变库,例如immer.js 。 这将允许您精确地在 state 中更新您想要更新的 select。
这将允许您像这样修改您的选项:
import produce from "immer"
const newOptions = produce(options, draftOptions => {
draftOptions[2].subOption[1] = [whatever you want]
})
setOptions(newOptions)
对于这种数据 model,我宁愿使用,useReducer 钩子。 就个人而言,我觉得它更干净。
但你的问题是,你没有变异并返回你的 subOptions 。
setOptions(
options.map((x, index) => {
if (index !== optionIndex) return x;
x.subOptions = x.subOptions.map((subItem, subIndex) => {
console.log(subItem);
if (subIndex !== subOptionIndex) return subItem;
return {
...subItem,
text: text
};
});
return x;
}),
);
按照您的解决方案,如果index === optionIndex
,您错过了在第一个map
中返回。
setOptions((options) => {
return options.map((x, index) => {
if (index !== optionIndex) return x;
return {
...x,
subOptions: x.subOptions.map((subItem, subIndex) => {
if (subIndex !== subOptionIndex) return subItem;
return {
...subItem,
text: text
};
})
}
})
})
否则你可以使用类似immer.js
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.