javascript - 从生产函数返回数组值 | immer.js
问题描述
我正在使用 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
解决方案
这段代码是一团糟。您正在使用map
which 返回一个新数组,但您还试图改变原始草稿对象。
这仍然是不可读和令人困惑的,但至少通过使用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;
}
});
}
});
});
推荐阅读
- python - File operations - filtering data from txt file in python
- java - 如何在对象列表中查找对象并通过其 ID 保存 - SpringBoot
- maven - 如何将集成测试工件临时放置到 Jenkins Workspace
- postgresql - 如何为 Liquibase 中的枚举添加新值?
- python - 通过“python -m pip install”安装需求随机抛出 WinError5 异常
- haskell - 数据类型声明中的 a 代表什么?
- sql - SQL 查询在 SSMS 中运行时间过长
- c# - 在 C# 中制作自定义堆栈
- autodesk-forge - 设计自动化工作项上的“failedLimitProcessingTime”
- matlab - 为什么我在尝试使用 HTTP 时在 MATLAB 中遇到身份验证错误