我的文件中有一个 prop
canPurchase
,我想使用减速器更新(切换)它。
当更新 prop
canPurchase
的逻辑位于同一文件中时,我的应用程序正在工作,但是当我将逻辑移出到减速器中时,它不起作用。我做错了什么?
burgerbuilder.js 文件:
class BurgerBuilder extends Component {
state = {
orderInProgress: false,
loading: false,
error: false
};
render() {
let burger = this.state.error ? (
<p>Ingredients can't be loaded </p>
) : (
<Spinner />
);
burger = (
<Aux>
<Burger ingredients={this.props.ings} />
<BuildControls
ingredientAdded={this.props.onIngredientAdded}
ingredientRemoved={this.props.onIngredientRemoved}
disabled={disabledInfo}
canPurchase={updatePurchaseState(this.props.ings)}
price={this.props.price}
ordered={this.orderInProgressHandler}
/>
</Aux>
);
}
return (
<Aux>
<Modal
show={this.state.orderInProgress}
modalClosed={this.orderCancelHandler}
/>
{burger}
</Aux>
);
}
}
/
const mapStateToProps = state => {
return {
ings: state.ingredients,
price: state.totalPrice,
canPurchase: state.canPurchase
};
};
const mapDispatchToProps = dispatch => {
return {
onIngredientAdded: ingNamePayload =>
dispatch({ type: actionTypes.ADD_INGREDIENT, payload: ingNamePayload }),
onIngredientRemoved: ingNamePayload =>
dispatch({ type: actionTypes.REMOVE_INGREDIENT, payload: ingNamePayload })
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(withErrorHandler(BurgerBuilder, axios));
reducer.js
import PropTypes from "react";
const initialState = {
ingredients: {
salad: 0,
bacon: 0,
cheese: 0,
meat: 0
},
totalPrice: 0,
canPurchase: false
};
const INGREDIENT_PRICES = {
salad: 0.5,
cheese: 0.4,
meat: 1.3,
bacon: 0.7
};
const updatePurchaseState = ingredients => {
const sum = Object.keys(ingredients)
.map(igKey => {
return ingredients[igKey];
})
.reduce((sum, el) => {
return sum + el;
}, 0);
return sum > 0;
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case actionTypes.ADD_INGREDIENT:
return {
...state,
ingredients: {
...state.ingredients,
[action.payload]: state.ingredients[action.payload] + 1
},
totalPrice: state.totalPrice + INGREDIENT_PRICES[action.payload],
canPurchase: updatePurchaseState(state.ingredients)
};
default:
return state;
}
};
export default reducer;
我正在切换的东西
<button onClick={props.ordered} className={classes.OrderButton} disabled={!props.canPurchase}>
ORDER NOW
</button>`
如果您需要更多信息,请告诉我。
谢谢你
this.orderInProgressHandler
在 BuildControls Component
中被称为有序道具,并使用 onClick
按钮。