我还处于非常初级的水平,我被困在这项任务上了.

Tasks

  1. 页面加载时,使用GET调用https://xc-countries-api.fly.dev/api/countries/的结果填充下拉菜单
  2. 从国家/地区下拉列表中 Select 一个国家/地区后,使用对https://xc-countries-api.fly.dev/api/countries/<Country_code&>/States/的GET调用结果填充第二个下拉列表

我无法从第二个API获取州数据.

感谢您抽出时间...

import { useState, useEffect } from "react";

const CountriesStates = () => {
    const [countries, setCountries] = useState([]);
    const [states, setStates] = useState([]);
    
    useEffect(() => {
        fetch('https://xc-countries-api.fly.dev/api/countries/')
            .then((response) => {
                return response.json();
            })
            .then((data) => {
                //console.log(data);
                setCountries(data); 
            })
    }, []);

    useEffect(() => {
        
        if(countries === 'default' || countries === '') {
            setStates([]);
        } else {
            fetch(`https://xc-countries-api.fly.dev/api/countries/${countries}/states/`)
                .then((response) => {
                    return response.json();
                })
                .then((data) => {
                    setStates(data);
                })
            }   
    }, [countries]);

    return (
        <>
            <div>
                <select name='countries' id='countries' style={{backgroundColor:'lightblue', borderRadius:'5px', fontSize:'1.3rem', marginRight:'3rem'}}>
                {
                    countries.map((country) => (                    
                            <option key={country.id}>{country.name}</option>                   
                    ))
                }
                </select>         
            </div>

            <div>
                <select name='states' id='states' style={{backgroundColor:'lightblue', borderRadius:'5px', fontSize:'1.3rem', marginRight:'3rem'}}>
                {
                    states.map((state) => (                    
                            <option key={state.id}>{state.name}</option>                   
                    ))
                }
                </select>         
            </div>
        </>
    );
};

export default CountriesStates;

推荐答案

对于所选国家/地区,需要添加一个新状态来存储和更新它.我添加了selectedCountry状态,然后每当从下拉列表中更改所选选项时设置它.
然后,只要 Select 了所选的国家/地区,就需要获取国家/地区.为此,需要在获取状态的useEffect依赖项中使用selectedCountry而不是countries.

CountriesStates.js:(增加了一些 comments 行)

import { useState, useEffect } from "react";

const CountriesStates = () => {
    const [countries, setCountries] = useState([]);
    const [states, setStates] = useState([]);
    // Store the selected country in a new state
    const [selectedCountry, setSelectedCountry] = useState();
    
    useEffect(() => {
        fetch('https://xc-countries-api.fly.dev/api/countries/')
            .then((response) => response.json())
            .then((data) => {
                setCountries(data); 
                // set the first country as selected automatically 
                setSelectedCountry(data[0]);
            })
    }, []);

    useEffect(() => {
        // If there's no selected country, then prevent sending an API request and clear the states
        if (!selectedCountry) {
           setStates([]);
           return;
        }

        fetch(`https://xc-countries-api.fly.dev/api/countries/${selectedCountry.code}/states/`)
          .then((response) => response.json())
          .then(setStates);
}   
    }, [selectedCountry]); // This useEffect should be rendered whenever the selected country is changed

    return (
        <>
            <div>
                <select 
                    name='countries' 
                    id='countries' 
                    style={{backgroundColor:'lightblue', borderRadius:'5px', fontSize:'1.3rem', marginRight:'3rem'}}
                    onChange={event => setSelectedCountry(countries.find(({ id }) => id.toString() === event.target.value.toString()))}>
                {
                    countries.map((country) => (
                         <option key={country.id} value={country.id}>{country.name}</option>                   
                    ))
                }
                </select>         
            </div>
           {!!states.length &&
              <div>
                  <select name='states' id='states' style={{backgroundColor:'lightblue', borderRadius:'5px', fontSize:'1.3rem', marginRight:'3rem'}}>
                  {
                      states.map((state) => (                    
                              <option key={state.id}>{state.name}</option>                   
                      ))
                  }
                  </select>         
              </div>
           }
        </>
    );
};

export default CountriesStates;

我还创建了一个DEMO LINK,以便轻松地对其进行审查和测试.

霍普,这很清楚,也很有帮助.

Reactjs相关问答推荐

实时收听react前端应用程序中的webhook响应

react应用程序中的字体不适用于.scss扩展名

CSS转换不适用于React MUI对象

我想将状态设置为true,直到每一张卡片都生成并在多姆中呈现

无法从正在使用Reaction的Electron 商务store 项目中的购物车中删除项目

生成Reaction Vite应用程序的停靠容器时无法识别环境变量

使用 MUI 菜单时添加新 html 元素时布局意外滚动跳转

错误:无法获取 RSC 负载.返回浏览器导航

太多的重新渲染 - React 中的无限循环.如何使用React.effect并使用fetch?

通过createRoot创建的React元素无法调用Provider值

为 Next.js 应用程序目录中的所有页面添加逻辑的全局文件是什么?

获取更多数据后更新 DOM,而不刷新 React.js 中的页面

如何根据用户在react.js中的 Select , Select 多个心形图标?

使用登录保护 React 中的 SPA 应用程序 - 为什么这种方法不起作用?

我应该如何将字符串作为props 传递给 React 组件?

为什么刷新页面时我的localStorage PET值变成空字符串?

将 useState 设置为组件内部的值

React js中不记名令牌中的空间问题

.filter() 函数在删除函数中创建循环 - React

运行开发服务器时如何为 Vite 指定运行时目录