[英]The browser makes 4 requests when sending data to the server
I am having problems with my react component.我的反应组件有问题。 The problem is that when I want to get the current geographic coordinates, I get them 4 times.
问题是当我想获取当前的地理坐标时,我得到了 4 次。 The same problem persists if I submit them to the server.
如果我将它们提交到服务器,同样的问题仍然存在。 The browser makes 4 identical requests instead of one.
浏览器发出 4 个相同的请求而不是 1 个。 What could be wrong?
有什么问题? This is the complete code for my component:
这是我的组件的完整代码:
import React from "react";
export const Component = (): JSX.Element => {
const getCoords = async (): Promise<GeolocationPosition> => {
return new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(
(position: GeolocationPosition) => resolve(position),
(error) => reject(error)
);
});
};
const getData = async () => {
const { latitude, longitude } = (await getCoords()).coords;
console.log(latitude + " " + longitude);
const response = await fetch(`URL`);
const result = await response.json();
console.log(result);
};
getData();
return (
<div>
<h1>Hello</h1>
</div>
);
};
You should not call API in the body ò function component.您不应在正文中调用 API ò function 组件。 You should call
getData
in the useEffect
:您应该在
useEffect
中调用getData
:
useEffect(() => {
const getCoords = async (): Promise<GeolocationPosition> => {
return new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(
(position: GeolocationPosition) => resolve(position),
(error) => reject(error)
);
});
};
const getData = async () => {
const { latitude, longitude } = (await getCoords()).coords;
console.log(latitude + " " + longitude);
const response = await fetch(`URL`);
const result = await response.json();
console.log(result);
};
getData();
}, []);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.