在写项目时遇到一些页面需要定义非常多的状态,这些数据还会给其他模块道出的组件和方法传递,再每次写传递数据时对极为不便,因为需要写很多入参,还要定义类型,就自定义了一个管理状态的hook
import { useState } from 'react';
// 自定义state hook 初始化的数据需要时对象格式
export function useSetState<T>(
_initialState: T | (() => T),
): [T, React.Dispatch<React.SetStateAction<Partial<T>>>] {
// 如果是初始化state是函数则调用函数赋值给state
if (_initialState instanceof Function && typeof _initialState === 'function') {
_initialState = _initialState();
}
const initialStateType = Object.prototype.toString.call(_initialState).slice(8, -1);
// undefined null之类抛出异常
if (!_initialState) {
throw new Error(`the useSetState initial state is ${initialStateType}`);
}
// 不是Object 抛出异常
if (_initialState && initialStateType !== 'Object') {
throw new Error('the useSetState initial state is not Object');
}
// 创建state
const [state, setState] = useState<T>(_initialState);
function setStateHandle(_memoizedState: T | ((value: T) => T)): void {
// 同一时间节点发生多次setState,这里拿到的state还是异步改变之前,需移入setState里面拿到对应的state
// if (typeof _memoizedState === 'function') {
// _memoizedState = _memoizedState(state);
// }
setState((_state) => {
// state是个异步操作,调用多次state需要从setState函数拿上一次state
if (_memoizedState instanceof Function && typeof _memoizedState === 'function') {
_memoizedState = _memoizedState(_state);
}
return {
..._state,
..._memoizedState,
};
});
}
// 返回state 和 setState
return [state, setStateHandle];
}
使用方面
export interface InitialStateType {
fileList: UploadFile[];
picList: Array<{ imageName: string; imageUrl: string; isError?: boolean; errorReason?: string }>;
activityList: ActivityServersType.ActivityItem[];
questionnaireCode: string;
formConfig: QuestionnaireServersType.QuestionnaireColumnsType;
listOpen: boolean;
questionnaireList: any[];
loading: boolean;
errorExcelUrl: string;
errorExcelList: string[];
errorPicListCard: Array<{ imageUrl: string; imageName: string; type: string }>;
uuid: string;
excelErrorShow: boolean;
}
const initialState: InitialStateType = {
fileList: [] as UploadFile[],
picList: [] as Array<{ imageName: string; imageUrl: string }>,
activityList: [] as any[],
questionnaireCode: '',
formConfig: {} as any,
listOpen: false,
questionnaireList: [],
loading: false,
errorExcelUrl: '',
errorExcelList: [],
errorPicListCard: [],
uuid: '',
excelErrorShow: false,
};
const [state, setState] = useSetState(initialState);
const {
picList,
activityList,
questionnaireCode,
formConfig,
listOpen,
questionnaireList,
loading,
errorExcelList,
uuid,
} = state;
setState({
activityList: res?.list,
});
就像使用setState一样,只不过初始值必须是对象,state包含了所有的数据,setState会把类型替换成可选