簡體   English   中英

如何在頁面加載時從 React js 中的 Api 調用填充選擇選項

[英]How to populate select options from an Api call in React js on page load

我正在嘗試使用頁面加載后來自 API 調用的值填充我的選擇下拉選項。 目前,只有在您觸摸並取消選擇選擇字段后才會生成選項。 在頁面加載時,選項不會被填充並且是空的。 我查看了建議使用 React-select 包的其他類似問題,但我正在尋找一種僅通過 react 來完成此操作的方法,但我沒有任何運氣找到解決方案。 請告知我如何實現這一目標或在哪里可以獲得幫助。 我在下面附上了我的代碼。 親切的問候。

import { Form } from "react-bootstrap";
import { Field, ErrorMessage } from "formik";
import axios from "axios";

function CompanySelect(props) {
  const [options, setOptions] = useState([]);

  useEffect(() => {
    const opt = [
      {
        key: "Select a company",
        value: "",
      },
    ];

    (async () => {
      const { data } = await axios.get("http://localhost:5000/api/company/");
      data.forEach((value) => {
        opt.push({
          key: value.name,
          value: value.id,
        });
      });
    })();

    setOptions(opt);
  }, []);

  const { label, name, ...rest } = props;

  return (
    <Form.Group className="mb-2">
      <Form.Label htmlFor={name}>{label}</Form.Label>
      <Field id={name} name={name} {...rest} as={Form.Select}>
        {options.map((option) => {
          return (
            <option key={option.value} value={option.value}>
              {option.key}
            </option>
          );
        })}
      </Field>
      <ErrorMessage className="text-danger" name={name} component={Form.Text} />
    </Form.Group>
  );
}

export default CompanySelect;

您在錯誤的時間更新您的狀態,就在觸發 async axios.get之后,但在結果實際出現之前 所以當狀態更新實際發生時,opt 還不包含從 axios 獲取的數據。 這是固定版本:

import { Form } from "react-bootstrap";
import { Field, ErrorMessage } from "formik";
import axios from "axios";

function CompanySelect(props) {
  const [options, setOptions] = useState([]);

  useEffect(() => {
    async function fetchData() {
      // Fetch data
      const { data } = await axios.get("http://localhost:5000/api/company/");
      const results = []
      // Store results in the results array
      data.forEach((value) => {
        results.push({
          key: value.name,
          value: value.id,
        });
      });
      // Update the options state
      setOptions([
        {key: 'Select a company', value: ''}, 
        ...results
      ])
    }

    // Trigger the fetch
    fetchData();
  }, []);

  const { label, name, ...rest } = props;

  return (
    <Form.Group className="mb-2">
      <Form.Label htmlFor={name}>{label}</Form.Label>
      <Field id={name} name={name} {...rest} as={Form.Select}>
        {options.map((option) => {
          return (
            <option key={option.value} value={option.value}>
              {option.key}
            </option>
          );
        })}
      </Field>
      <ErrorMessage className="text-danger" name={name} component={Form.Text} />
    </Form.Group>
  );
}

export default CompanySelect;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM