【问题标题】:ReactJs adding multiple reducers with contextReactJs 添加多个带上下文的减速器
【发布时间】:2020-06-05 21:28:13
【问题描述】:

我已经实现了单个减速器,但我想在这里添加多个减速器?我搜索了解决方案,但我仍然被困在这里

 1 - loginReducer.js
    export const loginReducer = (state, action) => {
        switch (action.type) {
          case 'LOGIN':
            return [
              ...state,
              {
                loggedIn: true,
              }
            ];
          case 'LOGOUT':
            loggedIn: false,

            return state ;
          default:
            return state;
        }
      };

2 - 提供者.js

import { loginReducer } from "./reducers/loginReducer";

const GlobalContext = React.createContext();
const GlobalProvider = props => {
  const [login, dispatch] = useReducer(loginReducer, []);
  return(
    <GlobalContext.Provider value={{login, dispatch}}> 
      {props.children}
    </GlobalContext.Provider>
  )
}

export default GlobalProvider;

如何添加另一个类似 loginReducer 的减速器?

这里要添加什么语法 GlobalContext.Provider value={{login, dispatch}}

【问题讨论】:

  • this 有帮助吗?

标签: reactjs react-redux reducers


【解决方案1】:

你可以使用 Array.prototype.reduce:

const reducerA = (state, action) => state + action;
const reducerB = (state, action) => state * action;
const rootReducer = (state, action) =>
  [reducerA, reducerB].reduce(
    (state, reducer) => reducer(state, action),
    state
  );
console.log('root reducer:',rootReducer(1, 2));

【讨论】:

  • 它工作正常,但是当我控制台没有从 reducerB @HMR 获取初始状态数据时
  • @ShibinRagh 这可能是因为你从reducerA获取初始状态,当reducerB第一次被调用时它得到reducerA的结果。也许您正在寻找的是您自己的combineReducers 版本?
猜你喜欢
  • 1970-01-01
  • 2019-11-02
  • 2018-11-20
  • 2020-04-22
  • 1970-01-01
  • 2017-02-26
  • 1970-01-01
  • 2021-12-08
  • 2021-10-13
相关资源
最近更新 更多