定义
// action-type的类型 export const UPDATE_EXPANDEDROW = 'UPDATE_EXPANDEDROW'; // state的类型 export type RowkeyType = PrimaryTableProps['expandedRowKeys']; // action的类型 type ExpandAction = { type?: typeof UPDATE_EXPANDEDROW; payload?: RowkeyType }; // reducer 的类型 export type ExpandReducer = React.Reducer<RowkeyType, ExpandAction>; // 创建上下文实例 export const ExpandContext: Context<{ state: RowkeyType; dispatch?: React.Dispatch<ExpandAction>; }> = createContext({ state: [] }); // reducer export const reducer: ExpandReducer = (state, action) => { switch (action.type) { case UPDATE_EXPANDEDROW: return action.payload; default: return state; } };
注入
const [state, dispatch] = useReducer<ExpandReducer>(reducer, innerExpandRowKeys); return ( <ExpandContext.Provider value={{ state, dispatch }}> <div> .... </ExpandContext.Provider> );
使用
const { dispatch } = useContext(ExpandContext); dispatch({ type: UPDATE_EXPANDEDROW, payload: thisExpandRowKeysNew });