TypeError: Assignment to constant variable When combine reducers

TypeError: Assignment to constant variable When combine reducers

我刚刚学习了 redux 并尝试使用 React + Redux 创建一个简单的商店应用程序。一切都很好,直到我尝试组合减速器

当我点击清除购物车时,出现错误“TypeError: Assignment to constant variable”

这是我之前的代码

index.js

function cartReducer(state, action) {
 switch (action.type) {
    case ADD_TO_CART: {
      return {
        cart: [
          ...state.cart,
          {
            product: action.productInfo,
            quantity: action.quantity,
          },
        ],
      };
    }
    
    case CLEAR_CART: {
          const new_state = { ...state };
          new_state.cart = [];
      return new_state;
    }

    default:
      return state;
  }
}

store.js

    function loadState(){
    try{
        const state = localStorage.getItem('cart');

        if(state !== null){
            return JSON.parse(state);
        }        
    } catch(e){
        // ignore errors
    }

    return {
        cart: []
    };
}
const store = createStore(
  cartReducer,
  loadState(),
  compose(
    applyMiddleware(thunk),
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
  )
);

这里是合并减速器后

index.js

export default function cartReducer(state, action) {

  switch (action.type) {
    case ADD_TO_CART: {
      return [
        ...state,
        {
          product: action.productInfo,
          quantity: action.quantity
        }
      ]
    }


    case CLEAR_CART: {
      const new_state = [...state];
      new_state = [];
      return new_state;
    }

    default:
      {
        if (state === undefined)
          return [];

        return state;
      }
  }
}

store.js

function loadState(){
    try{
        const state = localStorage.getItem('cart');

        if(state !== null){
            return JSON.parse(state);
        }        
    } catch(e){
        // ignore errors
    }

    return {
        cart: []
    };
}

const appReducers = combineReducers({
  cart: cartReducer,
});

const store = createStore(
  appReducers,
  loadState(),
  compose(
    applyMiddleware(thunk),
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
  )
);
    case CLEAR_CART: {
      const new_state = [...state]; // new_state is a constant
      new_state = []; // you can not assign it again
      return new_state;
    }

    // TO FIX IT:
    case CLEAR_CART: {
      return []; // that's enough
    }
case CLEAR_CART: {
    const new_state = [...state]; //clone
    new_state = [];
    return new_state;
}

问题是您正在覆盖“const new_state”

case CLEAR_CART: {
    return [];
}

试试这个。