【问题标题】:Using setInterval to call a react component function使用 setInterval 调用一个 react 组件函数
【发布时间】:2021-01-14 03:07:44
【问题描述】:

我创建了一个名为 IsLoggedIn 的函数,它使用带有 axios.get 的 useEffect 挂钩来查询服务器以获取用户的 cookie 会话时间。我想使用 setInterval 函数调用 IsLoggedIn,如下所示:

setInterval(<IsLoggedIn></IsLoggedIn>, 2000) //--> This is in app.js

但是,我收到一个错误:

    Uncaught SyntaxError: Unexpected identifier
    setInterval (async)
eval @ App.js:92
./src/App.js @ bundle.js:75202
__webpack_require__ @ bundle.js:790
fn @ bundle.js:101
eval @ index.js:6
./src/index.js @ bundle.js:75272
__webpack_require__ @ bundle.js:790
fn @ bundle.js:101
eval @ client:3
1 @ bundle.js:75389
__webpack_require__ @ bundle.js:790
(anonymous) @ bundle.js:857
(anonymous) @ bundle.js:860

如果有人对为什么会发生这种情况有任何想法,请告诉我。谢谢!

【问题讨论】:

  • 只需创建一个函数并在其中编写 axois 并在 setInterval 中调用该函数
  • @MUHAMMADILYAS axios 如何解决这个问题?它用于向外部资源发出 HTTP 请求。
  • @VinaySharma 在他想在某个时间间隔运行 http 请求并且他正在使用 axios 所以只是告诉他编写一个没有钩子的函数
  • @VinaySharma axios.get 在问题和 axios 用于 http 请求
  • 请从标题中正确阅读问题的性质,它无处询问有关 Axios 的任何信息。

标签: javascript reactjs setinterval


【解决方案1】:

有一些问题需要解决:

我创建了一个名为 IsLoggedIn 的函数,它使用了一个 useEffect 挂钩

假设你已经创建了一个自定义钩子,你不应该将它用作组件(),正确的方法是这样的:

const bla = useLoggedIn(); // custom hooks are also prefixed with 'use'

我想使用 setInterval 函数调用 IsLoggedIn

钩子只能在函数组件内部调用,所以最好将setInterval移动到自定义钩子的useEffect中。

【讨论】:

    【解决方案2】:

    自定义挂钩

    您所称的 React 组件函数似乎是 自定义 Hook。 Hooks 不是组件,而是具有重用状态逻辑机制的函数。

    关于自定义挂钩的要点:

    • 只能在功能组件中使用,不能在类组件中使用。
    • 不能像&lt;useFoo /&gt;那样以JSX的形式使用,需要像其他普通函数useFoo()一样调用。
    • 根据命名约定,它应该始终有一个use 前缀,后跟功能名称,这里是useIsLoggedIn

    您可以在official docsrules here 中阅读有关自定义挂钩的更多信息。

    解决方案

    
    // custom hook to query server for user's cookie session time
    const useLoggedIn = () => {
      useEffect(() => {
        // wrap the entire API call in a setInterval
        setInterval(() => {
          // axios call goes here
          // followed by some other computations
        }, 2000);
      }, []);
    
      // return value (if any)
    };
    
    const MyComponent = () => {
      // call the custom hook here instead of JSX
      useLoggedIn();
    
      return (
        <div>
          {/* rest of JSX */}
        </div>
      );
    };
    
    

    【讨论】:

      猜你喜欢
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-23
      • 1970-01-01
      • 2021-03-17
      • 2021-03-20
      相关资源
      最近更新 更多