【问题标题】:Why is this async function infinite looping?为什么这个异步函数无限循环?
【发布时间】:2021-10-16 02:23:31
【问题描述】:

我已将我的应用程序降至最低限度,以试图了解它为什么会无限循环......但我不明白。

const App = () => {

  console.log("just logging that the app ran!")
  
  const [data, setData] = useState('initial state');
  
  const getAsset = async () => {
  
    console.log("logging that getAsset ran!")

  setData("new state!")
  console.log(data)
}
  
  getAsset();
  
  return (

    <div >
      {data}
    </div>
  );
}

export default App;

任何指针?

错误信息:

react-dom.development.js:14997 Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

【问题讨论】:

标签: javascript reactjs asynchronous async-await


【解决方案1】:

只需在 useEffect 挂钩中调用 getAsset。不知道为什么这个函数是async。在您的情况下,setData 导致重新渲染并再次调用导致循环的 getAsset 函数

工作沙盒:https://codesandbox.io/s/react-hooks-example-forked-0rqb9?file=/src/App.js

const App = () => {

  const [data, setData] = useState("initial state");

  useEffect(() => {
    getAsset();
  }, []);

  const getAsset = async () => {
    setData("new state!");
  };

  return <div>{data}</div>;
};

export default App;

【讨论】:

    【解决方案2】:

    每次渲染组件时,您的代码都会调用 getAsset() 和 getAsset setState (setData) 并且当您更改状态时,组件会重新渲染,它会再次调用 getAsset 并再次重新渲染............

    你需要在挂载时调用它,所以使用 useEffect

    
    const App = () => {
    
      console.log("just logging that the app ran!")
      
      const [data, setData] = useState('initial state');
      
      const getAsset = async () => {
      
        console.log("logging that getAsset ran!")
    
      setData("new state!")
      console.log(data)
    }
     
     useEffect(() => {
    getAsset();
    
    },[])
    
      
      return (
    
        <div >
          {data}
        </div>
      );
    }
    
    export default App;
    

    【讨论】:

      【解决方案3】:

      问题在于,每次状态更改时,React 都会重新运行 App,这意味着直接在 App 中调用 getAsset 而无需检查它是否已经运行,这将导致循环。

      // Runs when the component is rendered.
      const App = () => {
        // ...
        getAsset(); // Sets state, re-rendering app.
        // ...
        return (
          <div >
            {data}
          </div>
        );
      }
      

      要解决此问题,请检查以确保仅设置一次状态或新状态何时不同,这样就不会发生循环行为。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-08-08
        • 1970-01-01
        • 1970-01-01
        • 2018-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多