繁体   English   中英

从生产函数返回数组值 | 沉浸式js

[英]Return array value from produce function | immer.js

我正在使用 immer.js 对状态中的数组执行操作。

数组:basicRecipe 和 recipeBasicRecipe。

我正在修改产品功能中的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返回一个新数组,但您也在尝试改变原始草稿对象。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM