【问题标题】:React-redux reducer without switch case没有开关盒的 React-redux 减速器
【发布时间】:2020-11-27 20:57:36
【问题描述】:

我正在为我的应用程序使用 react-redux。我面临一个问题。 我有以下产品减速器,但我不想使用开关盒,因为以下案例是我的不同产品屏幕。 在使用 switch 案例时,当我加载 vegProducts 时,优惠屏幕变空。

//在productsreducer中

  const initialState = {};
    
    export const productsReducer = (state = initialState, action) => {
      switch (action.type) {
        case SET_OFFERS:
          return {
            offers: action.offers,
          };
        case SET_VPRODUCTS:
          return {
            vegProducts: action.vegProducts,
          };
        case SET_NPRODUCTS:
          return {
            nvegProducts: action.nvegProducts,
          };
      }
      return state;
    };

我在我的 App.js 中调用不同的减速器,如下所示

import productsReducer from './store/reducers/products';
import cartReducer from './store/reducers/cart';
import ordersReducer from './store/reducers/orders';

const rootReducer = combineReducers({
  products: productsReducer,
  cart: cartReducer,
  orders: ordersReducer,
}); 

任何帮助将不胜感激,因为我花了将近 3 天的时间在互联网上搜索解决方案。

【问题讨论】:

    标签: react-native react-redux switch-statement action reducers


    【解决方案1】:

    您应该将数据附加到状态,而不是替换它。将其更改为:

      const initialState = {};
        
        export const productsReducer = (state = initialState, action) => {
          switch (action.type) {
            case SET_OFFERS:
              return {
                ...state, // <--- add this to append offers to state
                offers: action.offers,
              };
            case SET_VPRODUCTS:
              return {
                ...state, // <--- add this
                vegProducts: action.vegProducts,
              };
            case SET_NPRODUCTS:
              return {
                ...state, // <--- add this
                nvegProducts: action.nvegProducts,
              };
          }
          return state;
        };
    

    要了解它的工作原理:

    let state = {a: 1, b: 2} // <-- the state
    {...state} // {a: 1, b: 2} <-- spread operator spreads the properties of the object
    {b: 3} // {b: 3} <-- currently your doing this 
    {...state, b: 3} // {a: 1, b: 3} <-- you should instead append b to state, like this
    {...state, a: 5} // {a: 5, b: 2} <-- appending a to state
    

    【讨论】:

    • 真的很感谢你。好先生!再次感谢您。
    • @Sva 没问题,编码愉快 :)
    猜你喜欢
    • 2017-12-01
    • 1970-01-01
    • 2017-03-12
    • 1970-01-01
    • 2016-02-11
    • 2016-11-23
    • 2017-10-18
    • 2018-04-15
    • 1970-01-01
    相关资源
    最近更新 更多