将异步函数放入 useEffect 后出现错误 [英] Getting error after I put Async function in useEffect

查看:16
本文介绍了将异步函数放入 useEffect 后出现错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 useEffect 函数中,如果我只提到 getResults 函数变量,应用程序不会崩溃.但是当我在下面的代码中调用它时,我得到了这些错误:

In the useEffect function, if I just mention the getResults function variable, the app doesn't crash. But when I call it as I am doing in code below, I get these errors:

react-dom.development.js:21857 Uncaught TypeError: destroy is not a功能

react-dom.development.js:21857 Uncaught TypeError: destroy is not a function

考虑在树中添加错误边界以自​​定义错误处理行为.

Consider adding an error boundary to your tree to customize error handling behavior.

  function App() {
  const [foods, setFoods] = useState([]);
  const [isLoaded, setIsLoaded] = useState(false);
  useEffect(() => getResponse());
  const getResponse = async () => {
    const response = await fetch(sampleRequest);
    const data = await response.json();
    setFoods(data.hits);
  };
  let query = "Tomato";
  let sampleRequest = `https://api.edamam.com/search?q=${query}&app_id=${"1811484f"}&app_key=${"9cac93361efc99e2ebfbb8a453882af8"}`;

  return (
    <div className="App">
      <div className="main">
        <div className="navbars">
          {" "}
          <Navbars></Navbars>
        </div>
        <div className="listings">
          <Listing></Listing>
          <Listing></Listing>
          <Listing></Listing>
          <Listing></Listing>
          <Listing></Listing>
          <Listing></Listing>
          <Listing></Listing>
          <Listing></Listing>
          <Listing></Listing>
          <Listing></Listing>
        </div>
        <div className="footer">
          <h5>Made By YoYo Strangler in 2019</h5>
        </div>
      </div>
    </div>
  );
}

export default App;

推荐答案

您正在返回从 useEffect 函数调用 getResponse() 的结果.如果你从 useEffect 返回任何东西,它必须是一个函数.将代码更改为此应该可以解决它,因为您不再从 useEffect 函数返回任何内容.

You're returning the result of calling getResponse() from the useEffect function. If you return anything from useEffect, it has to be a function. Changing your code to this should fix it because you're no longer returning anything from the useEffect function.

useEffect(() => { 
  getResponse();
});

<小时>

useEffect 清理函数

如果您从 useEffect 挂钩函数返回任何内容,则它必须是 cleanup 函数.此函数将在组件卸载时运行.这可以认为大致相当于类组件中的 componentWillUnmount 生命周期方法.


The useEffect Cleanup Function

If you return anything from the useEffect hook function, it must be a cleanup function. This function will run when the component unmounts. This can be thought of as roughly equivalent to the componentWillUnmount lifecycle method in class components.

useEffect(() => { 
  doSomething();

  return () => {
    console.log("This will be logged on unmount");
  }
});

这篇关于将异步函数放入 useEffect 后出现错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆