简体   繁体   English

浏览器向服务器发送数据时发出 4 次请求

[英]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.

相关问题 在浏览器中本地存储数据并发送到服务器 - Storing data locally in browser and sending to server 将数据从浏览器发送到服务器并返回 - Sending data from a browser to a server and back 使用对服务器的字节范围请求时如何在浏览器中处理二进制数据 - How to handle binary data in the browser when using byte range requests to server 使用$ .when组合AJAX请求并将数据发送到函数 - Combining AJAX requests using $.when and sending the data to a function 如何规范向服务器发送请求? - How to regulate sending requests to server? 将加密的数据发送到服务器时,Javascript中的XSS - XSS in Javascript when sending encrypted data to server 发送套接字请求时浏览器内存泄漏 - Browser memory leak while sending socket requests 浏览器不发送CORS HTTP OPTION FOR POST REQUESTS - browser not sending CORS HTTP OPTION FOR POST REQUESTS Internet Explorer浏览器问题:浏览器未通过Ajax请求提交POST数据,服务器/客户端挂起 - Internet Explorer Browser Issue: Browser not submitting POST data with Ajax requests, server/client hangs 节点js向浏览器发送数据 - node js sending data to browser
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM