用自定义 hooks 管理请求状态
- 创建
hooks
interface State<D> {
data: D | null;
error: Error | null;
stat: 'loading' | 'success' | 'error' | 'idle';
};
const defaultState: State<null> = {
data: null,
error: null,
stat: 'idle',
};
export const useAsync = <D>(initState?: State) => {
const [state, setState] = useState({
...defaultState,
...initState
});
const setData = (data: D) => {
setState({
data,
error: null,
stat: 'success'
})
};
const setError = (error: Error) => {
setState({
data: null,
error,
stat: 'error'
})
};
const run = (promise: Promise) => {
if(!promise | !promise.then){
throw Error("请向run方法中传入promise对象")
}
promise.then((data) => {
setData(data);
return datal
})
.catch((error) => {
setError(error);
return error;
})
}
return {
setError,
setData,
run,
...state
}
}
- 使用 hooks
const { run, data, stat } = useAsync();
run("此处可以是执行的网络请求")