container: remove ingredient safely by passing disabledInfo

master
oscarzhou 2020-12-10 20:55:49 +13:00
parent 527168645e
commit 9a9f85110c
3 changed files with 39 additions and 5 deletions

View File

@ -5,8 +5,13 @@ import classes from './BuildControl.css';
const buildControl = (props) => ( const buildControl = (props) => (
<div className={classes.BuildControl}> <div className={classes.BuildControl}>
<div className={classes.Label}>{props.name}</div> <div className={classes.Label}>{props.name}</div>
<button className={classes.Less}>Less</button> <button
<button className={classes.More} onClick={props.added}>More</button> className={classes.Less}
onClick={props.removed}
disabled={props.disabled}>Less</button>
<button
className={classes.More}
onClick={props.added}>More</button>
</div> </div>
) )

View File

@ -16,7 +16,9 @@ const buildControls = (props) => (
<BuildControl <BuildControl
key={ctrl.name} key={ctrl.name}
name={ctrl.name} name={ctrl.name}
added={() => props.ingredientAdded(ctrl.type) }/> added={() => props.ingredientAdded(ctrl.type) }
removed={() => props.ingredientRemoved(ctrl.type)}
disabled={props.disabled[ctrl.type]} />
))} ))}
</div> </div>
) )

View File

@ -32,7 +32,8 @@ class BurgerBuilder extends Component {
updatedIngredient[type] = newCount; updatedIngredient[type] = newCount;
const priceAddition = INGREDIENT_PRICE[type]; const priceAddition = INGREDIENT_PRICE[type];
const newPrice = this.state.totalPrice + priceAddition; const oldPrice = this.state.totalPrice;
const newPrice = oldPrice + priceAddition;
this.setState({ this.setState({
totalPrice: newPrice, totalPrice: newPrice,
ingredients: updatedIngredient, ingredients: updatedIngredient,
@ -40,15 +41,41 @@ class BurgerBuilder extends Component {
} }
removeIngredientHandler = (type) => { removeIngredientHandler = (type) => {
const oldCount = this.state.ingredients[type];
if (oldCount <= 0){
return;
}
const newCount = oldCount - 1;
const updatedIngredient = {
...this.state.ingredients,
};
updatedIngredient[type] = newCount;
const priceDeduction = INGREDIENT_PRICE[type];
const oldPrice = this.state.totalPrice;
const newPrice = oldPrice - priceDeduction ;
this.setState({
totalPrice: newPrice,
ingredients: updatedIngredient,
});
} }
render() { render() {
const disabledInfo = {
...this.state.ingredients
};
for (let key in disabledInfo) {
disabledInfo[key] = disabledInfo[key] <= 0;
}
return ( return (
<Aux> <Aux>
<Burger ingredients={this.state.ingredients} /> <Burger ingredients={this.state.ingredients} />
<BuildControls <BuildControls
ingredientAdded={this.addIngredientHandler} /> ingredientAdded={this.addIngredientHandler}
ingredientRemoved={this.removeIngredientHandler}
disabled={disabledInfo} />
</Aux> </Aux>
); );
}; };