我创建了一个usePromise
React Hook,它应该能够解析各种 javascript 承诺并返回每个结果和状态:数据、解析状态和错误。我能够让它在没有任何参数的情况下传递函数,但是当我尝试更改它以允许参数时,我得到一个无限循环。
const usePromise = (promise: any): [any, boolean, any] => {
const [data, setData] = useState<object | null>(null);
const [error, setError] = useState<object | null>(null);
const [fetching, setFetchingState] = useState<boolean>(true);
useEffect(() => {
setFetchingState(true);
promise
.then((data: object) => {
setData(data);
})
.catch((error: object) => {
setError(error);
})
.finally(() => {
setFetchingState(false);
});
}, [promise]);
return [data, fetching, error];
};
const apiCall = (param?: string): Promise<any> => {
return new Promise(resolve => {
setTimeout(() => {
resolve({ response: `Response generated with your param ${param}.` });
}, 500);
});
};
const App = (): React.Element => {
// How can I pass an argument to apiCall?
const [response, fetching, error] = usePromise(apiCall(5));
console.log("render"); // This logs infinitely
return <div>{JSON.stringify({ response, fetching, error })}</div>;
};
您可以在以下位置检查工作代码(不带参数):https ://codesandbox.io/s/react-typescript-fl13w
和错误(标签卡住,请注意):https ://codesandbox.io/s/react-typescript-9ow82
注意:我想在不使用 NPM 或类似的 usePromise 单函数库的情况下找到解决方案