我已经实现了单个减速器,但是我想在这里添加多个减速器?我搜索以获取解决方案,但我仍然停留在这里
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-provider.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相同的reducer?
以及在此处添加什么语法GlobalContext.Provider value = {{login,dispatch}}
您可以使用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));