How can I dispatch function in redux?

前端 未结 1 764
不思量自难忘°
不思量自难忘° 2020-12-02 02:12

I have a Cart array in the redux store that contains all the items I added it to cart

like this

const initialState = {
  cart: [
    {
      product:         


        
相关标签:
1条回答
  • 2020-12-02 02:59

    My recommendation would be to not store redundant (derived) information in state. This means you don't need to (nor should you!) store the total in the state. The main reason this is a problem is that it gives your state an opportunity to contradict itself... if your state's total key doesn't equal the sum of the item totals, you've got a big problem!

    Instead, you can create a function that calculates the total and simply call that when you need it. For example:

    const calculateTotal = state => {
      let total = state.cart.reduce((total, item) => {
        return total + item.quantity * item.product.price 
      }, 0);
      // Assuming you just have one coupon, you could maintain a boolean in state
      if (state.hasCoupon) {
        total -= 50;
      }
      return total;
    }
    

    And then, anywhere in your code you need to get the total, you can simple use this function. It's not uncommon to include this sort of function in mapStateToProps:

    const mapStateToProps = state => ({
      total: calculateTotal(state);
    });
    

    If you end up with a lot of derived state, you may see some advantages from using a selector library like Reselect which can help you build selectors derived from other selectors and implements memoization for performance boosts.

    0 讨论(0)
提交回复
热议问题