本文主要是介绍ts版本react reducer,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
定义
// 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 });
这篇关于ts版本react reducer的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!