深度嵌套状态下的 Reducer
Reducer in deeply nested state
一段时间以来,我一直在尝试为深度嵌套状态想出一个 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],
};
一段时间以来,我一直在尝试为深度嵌套状态想出一个 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],
};