如何比较和深拷贝反应

问题描述

我是 React 新手,我有一个包含服务器数据的数组(简化)

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

一个来自 localStorage

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

我需要比较数组一中的 obj 是否等于数组二中的 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])

解决方法

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

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

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

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; }

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...