简体   繁体   English

Axios 调用在反应功能组件中运行两次

[英]Axios call runs twice in react functional component

Why does this fetched print twice?为什么这个 fetched 打印两次? When the axios call is put outside the function it only runs once.当 axios 调用放在 function 之外时,它只运行一次。


function App() {
  axios('https://www.google.com/').then(x => 
      console.log("fetched")
  )

  return (
    <div className="App">
    </div>
  );
}

export default App;

Do it in a useEffect hook.useEffect挂钩中执行此操作。

function App() {
  React.useEffect(() => {
    axios('https://www.google.com/').then(x => 
        console.log("fetched")
    )
  }, [])

  return (
    <div className="App">
    </div>
  );
}

export default App;

If you want a call to run only one time when the component is rendered, you should put it inside a useEffect.如果您希望在渲染组件时只运行一次调用,则应将其放在 useEffect 中。

useEffect(() => {
  axios('https://www.google.com/').then(x => 
      console.log("fetched")
  );
},[]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM