简体   繁体   English

如何在 React.Js Hook 中使用 SQL 查询值正确填充下拉列表

[英]How to properly Populate a Dropdown with SQL Query Values in React.Js Hook

I have a react component called Sidebar.jsx .我有一个名为Sidebar.jsx的反应组件。 Within it, I am making an API call to get a array of fleets to populate an eventual JSX dropdown element within my Sidebar.在其中,我进行 API 调用以获取一组车队,以在我的侧边栏中填充最终的 JSX 下拉元素。 This results in a simple JSON array.这会产生一个简单的 JSON 数组。

I have imported a function called getFleets() from my services folder to make the API call.我从我的服务文件夹中导入了一个名为 getFleets() 的函数来进行 API 调用。 The service uses the fetch API to make a query call to my backend and looks like this:该服务使用fetch API 对我的后端进行查询调用,如下所示:

export async function getFleets() {
    const resp = await fetch("http://localhost:5000/fleets", {
        method: 'GET',
        headers: {},
        mode: 'cors'
    });
    return resp.json();
};

However, when I use the website, it appears to infinitely make the API call.但是,当我使用该网站时,它似乎无限地进行 API 调用。 This is my first time trying to make an API call within a react component so I am a bit confused here.这是我第一次尝试在反应组件中进行 API 调用,所以我在这里有点困惑。 Other guides I've read online seem to be similar but I am obviously missing something.我在网上阅读的其他指南似乎相似,但我显然遗漏了一些东西。

What can I do to make this API call only once and retrieve my JSON array such that I can later use it to populate the options in my return ?我该怎么做才能使这个 API 调用一次并检索我的 JSON 数组,以便我以后可以使用它来填充我的 return 中的选项?

Sidebar.jsx

import React, { useEffect, useState } from "react";
import { getFleets } from "../services/FleetService";

const Sidebar = () => {
  const [data, setData] = useState([]);

  useEffect(() => {

    const setFleets = async () => {
        const fleets = await getFleets();
        console.log(fleets);
        setData(fleets);
      }
    setFleets();
  }, [data]);


  return (
    <>
    // Add data to <select> </select>
  );
};

The way your code works, since data is part of the dependency array sent to useEffect , every time data changes the effect runs, which changes data , which runs the effect again ...resulting in the infinite loop.您的代码的工作方式,因为data是发送到useEffect的依赖数组的一部分,所以每次data更改时效果都会运行,这会更改data ,从而再次运行效果......导致无限循环。

The simple fix is to remove data from the dependency array, and explicitly specifying an empty array [] as the second parameter of useEffect .简单的解决方法是从依赖数组中删除data ,并明确指定一个空数组[]作为useEffect的第二个参数。 This will make the effect run only exactly once, when the component is first rendered.这将使效果仅在首次渲染组件时运行一次。

You need to explicitly specify an empty array because when the second parameter isn't specified at all, the effect will run on every render, bringing back the infinite loop issue.您需要显式指定一个空数组,因为当根本没有指定第二个参数时,效果将在每个渲染上运行,从而导致无限循环问题。

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

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