我正在学习React,并且程序的大部分工作都在进行中,但是当我更新状态时,有一部分没有更新,我不确定为什么。
我有一个配料清单,一个配方清单(包含配料)和一个购物清单,其中包含一个配料清单,其数量与添加到购物清单中的所有配方相结合。
我将所有这些存储在状态中
state = {
ingredients: {},
instructions: {},
recipes: {},
shoppingList: {
ingredients: {}
}
}
当我添加配方时,将配方添加到配方中并将配方添加到购物清单中,这就是状态。如果我将食谱修改为需要2个西红柿而不是1个,那么购物清单将更新。但是,如果我在配方中添加了新成分,则购物清单不会使用新成分进行更新。我不确定为什么...
这是程序的其余代码:
addRecipe = recipe => {
// copy state
const recipes = { ...this.state.recipes };
// add recipe to copy
recipes[`recipe${Date.now()}`] = recipe;
// set state
this.setState({ recipes: recipes });
}
loadSampleRecipes = () => {
this.setState({ recipes: sampleRecipes });
}
addIngredient = ingredient => {
// copy state
const ingredients = { ...this.state.ingredients };
// add ingredient to copy
ingredients[`ingredient${Date.now()}`] = ingredient;
// set state
this.setState({ ingredients: ingredients });
}
updateIngredient = ingredient => {
// copy state
const ingredients = { ...this.state.ingredients };
ingredients[ingredient].price = 99;
// set state
this.setState({ ingredients: ingredients });
}
loadSampleIngredients = () => {
this.setState({ ingredients: sampleIngredients });
}
addIngredientToRecipe = (recipe, ingredient) => {
// copy state
const recipes = { ...this.state.recipes };
// add ingredient
recipes[recipe].ingredients[ingredient] = this.state.ingredients[ingredient];
recipes[recipe].ingredients[ingredient].qty = recipes[recipe].ingredients[ingredient].qty + 1 || 1; // not sure if this is needed
// set state
this.setState({ recipes: recipes });
}
deleteIngredientFromRecipe = (recipe, ingredient) => {
// copy state
const recipes = { ...this.state.recipes };
// remove ingredient from recipe
delete recipes[recipe].ingredients[ingredient];
// set state
this.setState({ recipes: recipes });
}
addIngredientsToShoppingList = (ingredients) => {
// copy state
const shoppingList = { ...this.state.shoppingList}
// add ingredient or increase qty
Object.keys(ingredients).forEach(ingredient => {
const newIngredient = ingredients[ingredient] // copy current incoming ingredient
// add qty together
if (shoppingList.ingredients[ingredient]) {
shoppingList.ingredients[ingredient].qty += newIngredient.qty;
} else {
shoppingList.ingredients[ingredient] = newIngredient;
}
});
console.log(shoppingList);
// set state
this.setState({ shoppingList: shoppingList });
}