首页 > 解决方案 > 从生产函数返回数组值 | 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

标签: javascriptarraysimmer.js

解决方案


这段代码是一团糟。您正在使用mapwhich 返回一个新数组,但您还试图改变原始草稿对象。

这仍然是不可读和令人困惑的,但至少通过使用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;
        }
      });
    }
  });
});

推荐阅读