Axios发送2个或更多请求

huangapple go评论65阅读模式
英文:

Axios sending 2 or more requests

问题

In this example, axios is sending two requests and the console.log is displaying two times because the useEffect hook is not properly set up to specify its dependencies. To ensure that the code within the useEffect hook runs only once, you should provide an empty array [] as the second argument to useEffect like this:

useEffect(() => {
  axios.get("test").then((data) => {
    console.log(data.data.test);
  });
}, []); // Empty dependency array

This way, the code inside useEffect will run only when the component mounts, preventing multiple requests and console.log calls.

英文:

Look at my simple code:

const Test= () => {
  useEffect(() => {
    axios.get("test").then((data) => {
      console.log(data.data.test);
    }, []);
  });

  return (
    <>
      <h1>Hello World</h1>
    </>
  );
};

In this example axios send request 2 times - I can see that in network tab and console.log is displaing 2 times. Do you know why?

答案1

得分: 1

你的React应用似乎被包裹在StrictMode中。如果你的应用在严格模式下运行,只有在开发环境中,组件会渲染两次。

英文:

It looks like your react app might be wrapped in StrictMode. If your app is wrapped in strict mode, only in development environment, the components gets rendered twice.

huangapple
  • 本文由 发表于 2023年5月11日 04:29:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76222328.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定