减速器处于深度嵌套状态



一段时间以来,我一直在尝试为深度嵌套状态设计一个useReducer。

const initialState = {
typeOfMeal: "breakfast",
protein: "",
carbs: "",
fat: "",
mainPhoto: "",
platePhoto: "",
ingredients: [
{
ingredientName: "",
ingredientQuantity: "",
ingredientUnit: "g",
ingredientId: 0,
},
],
};

配料中的对象是动态生成的,这很好,但我无法更新它们。这是负责更新这些对象的情况:

case "GET_INGREDIENT_BOX_VALUE":
return {
...state,
ingredients: [
...state.ingredients,
{ ...state.ingredients[action.index], [action.name]: action.value },
],
};

还有一个我想更新的对象片段的例子:

name="ingredientName"
value={state.ingredients[box.ingredientId].ingredientName}
onChange={(e) =>
dispatch({
type: "GET_INGREDIENT_BOX_VALUE",
value: e.target.value,
index: box.ingredientId,
name: e.target.name,
})
}

如何到达这样一个物体?我一直在寻找解决方案,但什么也找不到。谢谢你的帮助:(

希望这会有所帮助。

case "GET_INGREDIENT_BOX_VALUE":
const { ingredients } = state;
ingredients[action.index] = {
...ingredients[action.index],
[action.name]: action.value
};
return {
...state,
ingredients: [...ingredients],
};

最新更新