如何在React中调用Axios REST接口数据填充Material下拉菜单
问题原因
- 未声明响应式state存储接口返回的国家列表数据,渲染时使用的
array变量无实际值 - useEffect中仅定义了请求函数
getData,没有主动调用,接口请求不会触发 - 列表渲染时未添加
key属性,会触发React警告
完整实现代码
import { useState, useEffect } from 'react'; // 按需引入你使用的UI组件库的Select、MenuItem,示例默认是MUI组件 import Select from '@mui/material/Select'; import MenuItem from '@mui/material/MenuItem'; import { getCountries } from './你的接口文件路径'; import { CountriesDTO } from './types'; const CountrySelect = () => { // 存储国家列表数据 const [countryList, setCountryList] = useState<CountriesDTO[]>([]); // 可选:加载状态 const [loading, setLoading] = useState(false); // 可选:错误提示 const [errorMsg, setErrorMsg] = useState(''); useEffect(() => { const fetchCountryList = async () => { setLoading(true); try { const res = await getCountries(); // 将接口返回数据写入state setCountryList(res.data); setErrorMsg(''); } catch (err) { console.error('国家列表请求失败:', err); setErrorMsg('国家列表加载失败,请刷新重试'); } finally { setLoading(false); } }; // 主动触发请求 fetchCountryList(); }, []); return ( <div> {/* 错误提示 */} {errorMsg && <p style={{ color: '#f5222d', margin: '4px 0' }}>{errorMsg}</p>} <Select id="country-helper" disabled={loading} > {/* 加载状态占位 */} {loading ? ( <MenuItem value="" disabled>加载中...</MenuItem> ) : ( countryList.map((item) => ( // 必须添加key属性,使用唯一值code作为key <MenuItem key={item.code} value={item.code}> {item.country} </MenuItem> )) )} </Select> </div> ); }; export default CountrySelect;
补充说明
- 如果你的UI组件库不是MUI,只需要替换Select、MenuItem对应的组件标签即可,逻辑不需要改动
- 本地调试时如果接口跨域,需要配置后端CORS规则,或者在前端项目配置代理
- 不需要加载、错误状态的话可以直接删除对应逻辑,保留核心的state声明、请求触发、数据渲染三步即可
内容的提问来源于stack exchange,提问作者Peter Penzov
相关产品推荐
相关产品推荐

