英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论