我在使用Async函数后出现错误 [英] Getting error after i put Async function in useEffect

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

问题描述

在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'm doing in code below, i get these errors :

react-dom.development.js:21857未捕获的TypeError:destroy不是 功能

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");
  }
});

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

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