gpt4 book ai didi

javascript - 为嵌套对象数组创建reducer

转载 作者:行者123 更新时间:2023-12-01 01:59:49 25 4
gpt4 key购买 nike

我花了两天时间尝试创建reducer,将属性的 bool 值更改为Recipe,但没有成功。这是对象的嵌套数组。我无法继续前进这是数组的结构:

recipes: [ 
{ id: int,
re: 'string',
c: [
{ id: int,
co: 'string',
toRecipe: false
},
{...}
]
},
{...}
]

我创建了一个像这样的 reducer :

case actionTypes.EDIT_BOOLEAN:
return {
...state,
recipes: {...state.recipes,
[action.payload.idFromRecipe]: {...state.recipes[action.payload.idFromRecipe],
c: {...state.recipes[action.payload.idFromRecipe].c,
[action.payload.idFromComp]: {...state.recipes[action.payload.idFromRecipe].c[action.payload.idFromComp], toRecipe: false}
}
}
}
}

但是当我使用这个 reducer 时出现错误:类型错误:无法读取未定义的属性“c”

我在这里列出了这个数组(粗体文本):

class RecipeList extends Component {

render(){

console.log(this.props.recipes.map(recipe=>recipe));
let compons = this.props.recipes.map(recipe =>(
<div key={recipe.id}>
<h2>{recipe.re}</h2>
<ul key={recipe.id}>
{recipe.c.map(comp=> comp.toRecipe === true ?
<li key={comp.id}>{comp.co}</li>
: null
)}
</ul>
<div>
<form>
**{ recipe.c.map((comp, i)=>(
<div key={i}>
<input
onChange={()=>this.props.editRecipes(comp.id,recipe.id)}
type="checkbox"
key={i}
checked={comp.toRecipe}
/>
<label key={comp.id}>{comp.co}</label>

</div>
)) }**
</form>

</div>
</div>
)
);
console.log(compons);
return (
<div>
{compons}

</div>
)
}
}

有人可以帮助我吗?

最佳答案

You are trying to access property that doesn't exist yet

return {
...state,
recipes: {
...state.recipes,
[action.payload.idFromRecipe]: {
...state.recipes[action.payload.idFromRecipe],
c: {
...state.recipes[action.payload.idFromRecipe].c,
[action.payload.idFromComp]: {
...state.recipes[action.payload.idFromRecipe].c[action.payload.idFromComp],
toRecipe: false
}
}
}
}
};

所以基本上让我们举一个例子,你试图让嵌套对象工作。您的操作的有效负载为 idFromRecipe = "123",

are you entirely sure that state.recipes.123.c exist? because it seems like it doesn't so it returns undefined so lane  

...state.recipes[action.payload.idFromRecipe].c,

将失败,因为您无法访问未定义的属性 C。要使其像这样工作,您需要事先检查它是否存在,如

c: state.recipes[action.payload.idFromRecipe] ? {
...state.recipes[action.payload.idFromRecipe].c,
[action.payload.idFromComp]: {
...state.recipes[action.payload.idFromRecipe].c[action.payload.idFromComp],
toRecipe: false
}
} : {
...state.recipes[action.payload.idFromRecipe].c[action.payload.idFromComp],
toRecipe: false
}
}

通常,您应该避免这种构造,因为之后的逻辑非常奇怪,并且存在优化问题(因为您几乎每次都需要更改整个对象)。我的建议是使用 normalizr 实际上规范化状态,例如这样效果会更好,不会出现上面那种疯狂的逻辑。

关于javascript - 为嵌套对象数组创建reducer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50697210/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com