如何将功能逻辑移至减速器以更新状态

时间:2020-04-08 15:07:57

标签: javascript reactjs react-redux

我的文件canPurchase中有一个道具,我想使用reducer进行更新(切换)。

当用于更新prop canPurchase的逻辑在同一文件中时,我的应用程序正在工作,但是当我将逻辑移出到reducer时,它不起作用。我在做什么错了?

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>`

如果您需要更多信息,请告诉我。

谢谢

1 个答案:

答案 0 :(得分:0)

{this.orderInProgressHandler}在BuildControls组件中被称为有序道具,并使用onClick按钮,它的定义在哪里?