【发布时间】:2020-04-20 04:24:38
【问题描述】:
下面的帖子是关于创建一个用于获取数据的自定义钩子,它很简单。
https://dev.to/patrixr/react-writing-a-custom-api-hook-l16
虽然有一部分我不明白它是如何工作的。
为什么这个钩子会返回两次结果? (isLoading=true isLoading=false)
function useAPI(method, ...params) {
// ---- State
const [data, setData] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
// ---- API
const fetchData = async () => {
onError(null);
try {
setIsLoading(true);
setData(await APIService[method](...params));
} catch (e) {
setError(e);
} finally {
setIsLoading(false);
}
};
useEffect(() => { fetchData() }, []);
return [ data, isLoading, error, fetchData ];
}
function HomeScreen() {
const [ users, isLoading, error, retry ] = useAPI('loadUsers');
// --- Display error
if (error) {
return <ErrorPopup msg={error.message} retryCb={retry}></ErrorPopup>
}
// --- Template
return (
<View>
<LoadingSpinner loading={isLoading}></LoadingSpinner>
{
(users && users.length > 0) &&
<UserList users={users}></UserList>
}
</View>
)
【问题讨论】:
-
您希望发生什么?
标签: reactjs react-hooks