问题描述
我是 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
展开到一个新数组中,并使用对象解构来提取每个项目的 recipe
和 bookmarked
值。然后,您可以找出 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; }