【问题标题】:How to compare and deep copy react如何比较和深拷贝反应
【发布时间】:2021-01-13 20:41:42
【问题描述】:

我是 React 新手,我有服务器数据数组(简化)

let recipes = [
  {"recipe": {label: "Chicken Vesuvio"},"bookmarked":false,"bought":false},
  {"recipe": {label: "Chicken Paprikash"},"bookmarked":false,"bought":false},
  {"recipe": {label: "Baked Chicken"},"bookmarked":false,"bought":false},
  {"recipe": {label: "Chicken Liver Pâté"},"bookmarked":false,"bought":false}
]

还有一个来自localStorage的

let localRecipes = [
  {"recipe": {label: "Chicken Vesuvio"},"bookmarked":true,"bought":false},
  {"recipe": {label: "Chicken Paprikash"},"bookmarked":true,"bought":false},
]  

我需要比较数组 1 中的 obj 是否等于数组 2 中的 obj,将第一个数组中的书签值更改为 true 并返回数组的副本。我没有任何 id,所以我使用标签进行比较。这是我的代码,它可以工作,但它不会返回副本,它会改变原始代码。

 useEffect(() => {
    if(recipes && recipes.length) {
        for (let i = 0; i < localRecipes.length; i++) {
            if(recipes[i].recipe.label == localRecipes[i].recipe.label) {
                recipes[i].bookmarked = true
            }
        }
    }
}, [isFetching])

【问题讨论】:

标签: javascript reactjs deep-copy


【解决方案1】:

您可以将recipes 展开到一个新数组中,并使用对象解构来提取每个项目的recipebookmarked 值。然后,您可以找出localRecipes 中每个项目的bookmarked 状态。

const recipes = [
  { "recipe": { "label": "Chicken Vesuvio"    }, "bookmarked": false, "bought":false },
  { "recipe": { "label": "Chicken Paprikash"  }, "bookmarked": false, "bought":false },
  { "recipe": { "label": "Baked Chicken"      }, "bookmarked": false, "bought":false },
  { "recipe": { "label": "Chicken Liver Pâté" }, "bookmarked": false, "bought":false }
];

const localRecipes = [
  { "recipe": { "label": "Chicken Vesuvio"   }, "bookmarked": true, "bought": false },
  { "recipe": { "label": "Chicken Paprikash" }, "bookmarked": true, "bought": false },
];

const merged = [
  ...recipes.map(({ recipe, bookmarked, ...rest }) => ({
    ...rest,
    recipe,
    bookmarked: localRecipes
      .find(({ recipe: { label } }) => label === recipe.label)
        ?.bookmarked || bookmarked
  }))
]

console.log(merged);  // Merge remote with local storage
console.log(recipes); // Remote is uneffected
.as-console-wrapper { top: 0; max-height: 100% !important; }

【讨论】:

    猜你喜欢
    • 2012-04-12
    • 2015-01-13
    • 1970-01-01
    • 1970-01-01
    • 2012-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多