从下拉列表中动态创建选项

发布于 2025-02-13 17:52:01 字数 2146 浏览 2 评论 0原文

因此,我正在尝试动态创建选择下拉菜单的选项,我将API与我的国家状态进行获取,但是我不知道如何访问每个对象内的内容

。下面,数据正在从API中提取,也就是说,获取工作,但是我不知道如何创建每个对象中选择的选项。

import { EmailIcon, LocationIcon } from './assets/FormSvgIcons'
import { useEffect, useState } from 'react';

const SettingsForm = () => {
 const [stateList, setStateList] = useState([]);
 const [userLocation, setUserLocation] = useState('');

 const handleLocation = () => {
    setUserLocation(e.target.value);
 }

 useEffect(() => {
    let initialStates = [];

    fetch('https://servicodados.ibge.gov.br/api/v1/localidades/estados/')
        .then(response => {
            return response.json();
        }).then(data => {
            initialStates = data.map((states) => {
                return states
            });
            console.log(initialStates);
            setStateList({states: initialStates});
        });
 }, []);

 const createDropdownOptions = () => {
    const createOptions = stateList.map((state, i) => {
        Object.keys(state).map(singleState => (
            <option value={i}>{singleState.sigla}</option>
        ))
    });
    return createOptions;
 }

 return (
 <form>
    <div className="user-country">
            <label className="white-label">
                Local
            </label>
            <div className="input-icon-wrapper">
                <div className="icon-input w-embed">
                    <LocationIcon />
                </div>
                <select 
                    className="select-field white-select w-select"
                    id="locationField"
                    name="locationField"
                    onChange={handleLocation}
                >
                    {createDropdownOptions()}
                </select>
            </div>
        </div>
 </form>
 )

我知道错误在createRopDownOptions函数中,因为它负责创建选项,但是我不知道该怎么做,有光吗?

So, I'm trying to dynamically create the options of a select dropdown, I make the fetch of an api with the states of my country, but I don't know how to access the content inside each object..

As you can see below, the data is being pulled from the API, that is, the fetch worked, but I don't know how to create the options that will be inside the Select with each object..
d

import { EmailIcon, LocationIcon } from './assets/FormSvgIcons'
import { useEffect, useState } from 'react';

const SettingsForm = () => {
 const [stateList, setStateList] = useState([]);
 const [userLocation, setUserLocation] = useState('');

 const handleLocation = () => {
    setUserLocation(e.target.value);
 }

 useEffect(() => {
    let initialStates = [];

    fetch('https://servicodados.ibge.gov.br/api/v1/localidades/estados/')
        .then(response => {
            return response.json();
        }).then(data => {
            initialStates = data.map((states) => {
                return states
            });
            console.log(initialStates);
            setStateList({states: initialStates});
        });
 }, []);

 const createDropdownOptions = () => {
    const createOptions = stateList.map((state, i) => {
        Object.keys(state).map(singleState => (
            <option value={i}>{singleState.sigla}</option>
        ))
    });
    return createOptions;
 }

 return (
 <form>
    <div className="user-country">
            <label className="white-label">
                Local
            </label>
            <div className="input-icon-wrapper">
                <div className="icon-input w-embed">
                    <LocationIcon />
                </div>
                <select 
                    className="select-field white-select w-select"
                    id="locationField"
                    name="locationField"
                    onChange={handleLocation}
                >
                    {createDropdownOptions()}
                </select>
            </div>
        </div>
 </form>
 )

I know that the error is in the createDropdownOptions function because it is responsible for creating the options, but I don't know how to do it, any light?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

慕巷 2025-02-20 17:52:01

我看到您的问题,您的逻辑是正确的,但是实现不佳,一旦您过滤了数据,它才会呈现一个新组件:

import { EmailIcon, LocationIcon } from "./assets/FormSvgIcons";
import React, { useEffect, useState } from "react";

export default function SettingsForm() {
  const [stateList, setStateList] = useState([]);

  useEffect(() => {
    fetch("https://servicodados.ibge.gov.br/api/v1/localidades/estados/")
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        console.log(data);
        setStateList(data);
      });
  }, []);

  return (
    <form>
      <div className="user-country">
        <label className="white-label">Local</label>
        <div className="input-icon-wrapper">
          <div className="icon-input w-embed">
            <LocationIcon />
          </div>
          <select
            className="select-field white-select w-select"
            id="locationField"
            name="locationField"
            onChange={handleLocation}
          >
            {stateList.map((state) => {
              return <CreateDropdownOptions state={state} />;
            })}
          </select>
        </div>
      </div>
    </form>
  );
}

function CreateDropdownOptions({ state }) {
  return (
    <option key={state.id} value={state.sigla}>
      {state.sigla}
    </option>
  );
}

我建议为每个选项使用一个组件,如果您以后需要使用一个组件,那么它将变得更加容易对

I see your problem, your logic is correct, but it is poorly implemented, once you have filtered the data, it is only rendering a new component:

import { EmailIcon, LocationIcon } from "./assets/FormSvgIcons";
import React, { useEffect, useState } from "react";

export default function SettingsForm() {
  const [stateList, setStateList] = useState([]);

  useEffect(() => {
    fetch("https://servicodados.ibge.gov.br/api/v1/localidades/estados/")
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        console.log(data);
        setStateList(data);
      });
  }, []);

  return (
    <form>
      <div className="user-country">
        <label className="white-label">Local</label>
        <div className="input-icon-wrapper">
          <div className="icon-input w-embed">
            <LocationIcon />
          </div>
          <select
            className="select-field white-select w-select"
            id="locationField"
            name="locationField"
            onChange={handleLocation}
          >
            {stateList.map((state) => {
              return <CreateDropdownOptions state={state} />;
            })}
          </select>
        </div>
      </div>
    </form>
  );
}

function CreateDropdownOptions({ state }) {
  return (
    <option key={state.id} value={state.sigla}>
      {state.sigla}
    </option>
  );
}

I recommend using a component for each option, this will make it easier if you later need to do some action on the

┊风居住的梦幻卍 2025-02-20 17:52:01

首先,您可以简化使用到下面的代码。当您制作MAP时,回调返回每个迭代的相同对象,更好地使用data,因为输出将相同。

useEffect(() => {
  fetch("https://servicodados.ibge.gov.br/api/v1/localidades/estados/")
    .then((response) => {
      return response.json();
    })
    .then((data) => {
      console.log(data);
      setStateList(data);
    });
}, []);

然后将CreateRopDownOptions更改为以下代码。您可以更改value或显示给nome的内容:

const createDropdownOptions = () => {
  const createOptions = stateList.map((state) => (
    <option key={state.id} value={state.sigla}>
      {state.sigla}
    </option>
  ));
  return createOptions;
};

finnaly您需要将事件传递给handlelelocation

const handleLocation = (e) => {
    setUserLocation(e.target.value);
 }

First you could simplify your useEffect to the code below. As you are making a map where the callback returns the same object for each iteration, better you use data as it's, because the output would be the same.

useEffect(() => {
  fetch("https://servicodados.ibge.gov.br/api/v1/localidades/estados/")
    .then((response) => {
      return response.json();
    })
    .then((data) => {
      console.log(data);
      setStateList(data);
    });
}, []);

Then change createDropdownOptions to the code below. You can change the value or what's displayed to nome:

const createDropdownOptions = () => {
  const createOptions = stateList.map((state) => (
    <option key={state.id} value={state.sigla}>
      {state.sigla}
    </option>
  ));
  return createOptions;
};

And finnaly you would need to pass the event to handleLocation:

const handleLocation = (e) => {
    setUserLocation(e.target.value);
 }
樱娆 2025-02-20 17:52:01

不要过度思考。提示:

  • 保持您的提取逻辑尽可能简单。
  • 更喜欢异步等待,而不是链接以获得可读性。
  • 尊重您的国家初始化。如果您说这是一个数组,请不要将其设置为对象。

如果您有数组,则可以轻松地将其映射到JSX中并生成您的选项。
您做得很好,非常接近。看看我为使其工作所做的更改:

import { useEffect, useState } from 'react';

export const SettingsForm = () => {
  const [stateList, setStateList] = useState([]);
  const [userLocation, setUserLocation] = useState('');

  const handleLocation = () => {
    setUserLocation(e.target.value);
  };

  useEffect(() => {
    const loadOptions = async () => {
      const data = await fetch(
        'https://servicodados.ibge.gov.br/api/v1/localidades/estados/'
      ).then((response) => {
        return response.json();
      });

      setStateList(data);
    };
    loadOptions();
  }, []);

  
  return (
    <form>
      <div className="user-country">
        <label className="white-label">Local</label>
        <div className="input-icon-wrapper">
          <div className="icon-input w-embed"></div>
          <select
            className="select-field white-select w-select"
            id="locationField"
            name="locationField"
            onChange={handleLocation}
          >
            {stateList.map((state) => {
              return (
                <option key={state.nome} value={state.nome}>
                  {state.sigla}
                </option>
              );
            })}
          </select>
        </div>
      </div>
    </form>
  );
};

希望它有帮助!保持良好的工作,并随时伸出手,以防您仍然卡住!

Don't overthink. Tips:

  • Keep your fetching logic as simple as possible.
  • Prefer Async Await instead of then chaining for readability.
  • Honor your state initialization. If you said it is an Array, don't set it as an object.

If you have an array, you can easily map it into jsx and generate your options.
You did very well, and got really close. Take a look at the changes I've done to get it working:

import { useEffect, useState } from 'react';

export const SettingsForm = () => {
  const [stateList, setStateList] = useState([]);
  const [userLocation, setUserLocation] = useState('');

  const handleLocation = () => {
    setUserLocation(e.target.value);
  };

  useEffect(() => {
    const loadOptions = async () => {
      const data = await fetch(
        'https://servicodados.ibge.gov.br/api/v1/localidades/estados/'
      ).then((response) => {
        return response.json();
      });

      setStateList(data);
    };
    loadOptions();
  }, []);

  
  return (
    <form>
      <div className="user-country">
        <label className="white-label">Local</label>
        <div className="input-icon-wrapper">
          <div className="icon-input w-embed"></div>
          <select
            className="select-field white-select w-select"
            id="locationField"
            name="locationField"
            onChange={handleLocation}
          >
            {stateList.map((state) => {
              return (
                <option key={state.nome} value={state.nome}>
                  {state.sigla}
                </option>
              );
            })}
          </select>
        </div>
      </div>
    </form>
  );
};

Hope it helps! keep up the good work and feel free to reach out in case you're still stuck!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文