You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
typeA=any;typeB=any;typeSTATE={a: A;b: B;}typeACTION=|{type: 'changeA',payload: any}|{type: 'changeB',payload: any}typeREDUCER=<Textends{}>(state: T,action: ACTION)=>STATEtypeSLICES={a: REDUCER<A>;b: REDUCER<B>;}// reduce 写法constcombineReducers=(slices: SLICES)=>(state:STATE,action:ACTION):STATE=>// use for..in loop, if you prefer itObject.keys(slices).reduce((state,key)=>({
...acc,[key]: slices[key](state[key],action),}),state);// for...in 写法constcombineReducers=(slices: SLICES)=>(state:STATE,action:ACTION):STATE=>{letnewState={}for(let[key,reducer]ofObject.entries(slices)){newState={
...state,[key]: reducer(state[key],action)}}returnnewState}
Example:
importafrom"./Reducer1";importbfrom"./Reducer2";constinitialState={a: {},b: {}};// some state for props a, bconstrootReducer=combineReducers({ a, b });constStoreProvider=({ children })=>{const[state,dispatch]=useReducer(rootReducer,initialState);// Important(!): memoize array value. Else all context consumers update on *every* renderconststore=React.useMemo(()=>[state,dispatch],[state]);return(<StoreContext.Providervalue={store}>{children}</StoreContext.Provider>);};
const[s1,d1]=useReducer(a,{});// some init state {} const[s2,d2]=useReducer(b,{});// some init state {} // don't forget to memoize againconstcombinedDispatch=React.useCallback(combineDispatch(d1,d2),[d1,d2]);constcombinedState=React.useMemo(()=>({ s1, s2,}),[s1,s2]);// This example uses separate dispatch and state contexts for better render performance<DispatchContext.Providervalue={combinedDispatch}><StateContext.Providervalue={combinedState}>{children}</StateContext.Provider></DispatchContext.Provider>;
In summary
Above are the most common variants. There are also libraries like use-combined-reducers for these cases. Last, take a look at following sample combining both combineReducers and reduceReducers
The text was updated successfully, but these errors were encountered:
useReducer - combine reducers
参考链接:React useReducer: How to combine multiple reducers?
原文+注解
Combine slice reducers (
combineReducers
)The most common approach is to let each reducer manage its own property ("slice") of the state:
Example:
Combine reducers in sequence
Apply multiple reducers in sequence on state with arbitrary shape, akin to reduce-reducers:
Example:
Combine multiple
useReducer
HooksYou could also combine dispatch and/or state from multiple
useReducer
s, like:Example:
In summary
Above are the most common variants. There are also libraries like
use-combined-reducers
for these cases. Last, take a look at following sample combining bothcombineReducers
andreduceReducers
The text was updated successfully, but these errors were encountered: