【发布时间】:2019-10-08 10:32:28
【问题描述】:
我有一个具体案例。我做的第一件事是请求 Index.DB。从它获得 taskId 后,我需要开始每 5 秒询问一次服务器。并停止在特定标志上执行此操作。我怎样才能用钩子正确地做到这一点?
我尝试像这样使用 useInterval 钩子: https://github.com/donavon/use-interval; 但是当我在 useEffect 中设置它时会导致一致的错误:
无效的挂钩调用。 Hooks 只能在函数组件的主体内部调用。
const Page = () => {
const [task, setTask] = useState({})
const isLoaded = (task.status === 'fatal');
const getTask = (uuid: string) => {
fetch(`${TASK_REQUEST_URL}${uuid}`)
.then(res => {
return res.json();
})
.then(json => {
setTask(json.status)
})
.catch(error => console.error(error));
};
useEffect(() => {
Storage.get('taskId')
.then(taskId => {
if (!taskId) {
Router.push('/');
}
useInterval(() => getTask(taskId), 5000, isTaskStatusEqualsSomthing)
})
}, []);
return (
<p>view</p>
);
};
我也尝试过这样玩原生 setInterval
useEffect(() => {
Storage.get('taskId')
.then(taskId => {
if (!taskId) {
Router.push('/');
}
setInterval(() => getTask(taskId), 5000)
})
}, []);
但在这种情况下,我不知道如何清除Interval,而且代码看起来很脏。
【问题讨论】:
-
你使用的是哪个 react 版本?
标签: reactjs react-hooks