【问题标题】:Request to server each N seconds after flag标记后每 N 秒向服务器请求一次
【发布时间】: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


【解决方案1】:

解决方案很简单。你只需要在.then 回调中配置你的 setInterval 就像

useEffect(() => {
    let timer;
    Storage.get('taskId')
     .then(taskId => {
         if (!taskId) {
            Router.push('/');
         else {
            timer = setInterval(() => getTask(taskId), 5000)
         }
      }

     })
     return () => {clearInterval(timer)}
}, []);

原因,第一种方法对您不起作用是因为您不能像 useInterval 那样有条件地或在 useEffect 中调用钩子

【讨论】:

  • 您的意思是说它有条件地以 then 或 catch 可以运行的方式运行,因此它违反了钩子规则。我们不能使用 Promise.finally 吗?它将无条件运行。
  • 那是错误的解决方案。那我如何清除标志上的Interval?如果 (isLoaded) { ... ?}
  • clearInterval 在组件卸载时运行,如果您设置了收到 taskId 后将设置的计时器变量集,它将起作用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多