我使用immer.js在状态中的数组上执行操作。
数组: basicRecipe和recipeBasicRecipe。
我正在修改produce函数中的draft.basicRecipe。我的目标是返回更新后的"draft.basicRecipe“值并将其存储在temparray1中。
let temparray1 = produce(state, draft => {
draft.basicRecipe = draft.basicRecipe.map(item => {
let element = draft.recipeBasicRecipes.find(e => e._id === item._id);
console.log(element);
if (element) {
item.details = item.details.map(e => {
let detail = element.details.find(d => d._id === e._id);
if (detail) {
e.rate = detail.rate;
}
return e;
});
}
return item;
});
return draft.basicRecipe;
});
console.log(temparray1);当我返回草稿时,我能够看到更新的basicRecipe嵌套在输出中。当我尝试返回数组(即draft.basicRecipe )时,会出现以下错误
[Immer] An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft发布于 2020-10-22 11:26:32
这段代码乱七八糟。您正在使用map,它返回一个新的数组,但是您还试图改变原始的draft对象。
这仍然是不可读和令人困惑的,但至少通过使用forEach而不是map,我们只是在改变,而不是试图同时做两件事。
let temparray1 = produce(state, (draft) => {
draft.basicRecipe.forEach((item) => {
let element = draft.recipeBasicRecipes.find((e) => e._id === item._id);
if (element) {
item.details.forEach((e) => {
let detail = element.details.find((d) => d._id === e._id);
if (detail) {
e.rate = detail.rate;
}
});
}
});
});https://stackoverflow.com/questions/63559024
复制相似问题