我正在尝试编写一个使用react-query
中的useQuery
的自定义挂钩。自定义挂钩接收员工的id
,获取一些数据并将其返回给消费组件。我希望能够dispatch
一个redux操作来显示加载指示符,或者在失败时显示错误消息。这是我定制的钩子。
export default function useEmployee(id) {
const initial = {
name: '',
address: '',
}
const query = useQuery(['fetchEmployee', id], () => getEmployee(id), {
initialData: initial,
onSettled: () => dispatch(clearWaiting()),
onError: (err) => dispatch(showError(err)),
})
if (query.isFetching || query.isLoading) {
dispatch(setWaiting())
}
return query.data
}
当我刷新页面时,我在浏览器控制台中收到了这个错误,我不知道如何修复这个错误?
Warning: Cannot update a component (`WaitIndicator`) while rendering a different component (`About`).
To locate the bad setState() call inside `About`, follow the stack trace as described in
问题可能是在任何组件生命周期(即useEffect
(之外调度setWaiting
操作。将调度逻辑移动到具有适当依赖关系的useEffect
钩子中。
示例:
export default function useEmployee(id) {
const initial = {
name: '',
address: '',
};
const { data, isFetching, isLoading } = useQuery(['fetchEmployee', id], () => getEmployee(id), {
initialData: initial,
onSettled: () => dispatch(clearWaiting()),
onError: (err) => dispatch(showError(err)),
});
useEffect(() => {
if (isFetching || isLoading) {
dispatch(setWaiting());
}
}, [isFetching, isLoading]);
return data;
}