
本文解决使用 mui `autocomplete` 组件时,状态已正确选中但关联内容无法渲染的问题,核心在于修复 `renderselectedstatewithmap` 函数未返回 jsx 的逻辑缺陷,并提供可复用、带键值和类型安全的渲染方案。
在 React 中,组件函数必须显式返回 JSX 才能被渲染到 DOM;而原代码中 renderSelectedStateWithMap 内部虽调用了 map(),却未将结果返回,导致函数实际返回 undefined,因此
以下是修正后的完整实现(含关键优化):
import { Autocomplete, TextField } from '@mui/material';
import { useState } from 'react';
import styles from './styles.module.css';
type Location = {
name: string;
address: string;
lat: number;
lng: number;
};
type StateData = {
name: string;
locations: Location[];
};
const statesString = [
'Acre', 'Alagoas', 'Amazonas', 'Brasília Distrito Federal',
'Ceará', 'Espírito Santo', 'Goiás', 'Maranhão', 'Mato Grosso',
'Mato Grosso do Sul', 'Minas Gerais', 'Pará', 'Paraíba', 'Paraná',
'Pernambuco', 'Piauí', 'Rio de Janeiro', 'Rio Grande do Norte',
'Rio Grande do Sul', 'Roraima', 'Santa Catarina', 'São Paulo',
'Sergipe', 'Tocantins',
];
const locations: StateData[] = [
{
name: 'Acre',
locations: [
{
name: 'Aeroporto de Rio Branco',
address: 'Avenida Plácido de Castro – Vila Aeroporto – Rio Branco CEP: 69923-900 AC Telefone: 68-3211-1000',
lat: -9.98417,
lng: -67.88333,
},
],
},
// 可扩展其他州数据(如:{ name: 'São Paulo', locations: [...] })
];
export default function SearchBar() {
const [selectedState, setSelectedState] = useState(null);
const renderSelectedStateWithMap = (stateName: string | null) => {
if (!stateName) return null;
const state = locations.find((s) => s.name === stateName);
if (!state || state.locations.length === 0) return null;
return (
? {state.name} 的地点
{state.locations.map((location, idx) => (
{location.name}
{location.address}
坐标: ({location.lat.toFixed(5)}, {location.lng.toFixed(5)})
))}
);
};
return (
setSelectedState(newValue)}
renderInput={(params) => (
)}
sx={{ width: 300 }}
/>
{renderSelectedStateWithMap(selectedState)}
);
} ✅ 关键改进说明:
- 使用 find() 替代嵌套 map() + 条件判断,语义更清晰、性能更优;
- 显式返回 JSX 片段(包裹),并添加空值防护(!stateName / !state);
- 为每个 location 添加唯一 key(如 key={loc-${idx}}),避免 React 警告;
- 将 selectedState 类型设为 string | null,并同步绑定 value 属性,确保受控组件行为一致;
- 支持扩展多州数据(只需向 locations 数组添加对象即可)。
⚠️ 注意事项:
- 若 locations 数据量较大,建议配合 useMemo 缓存渲染结果;
- 生产环境应避免内联函数(如 renderSelectedStateWithMap)在渲染中定义,可提取为独立组件或使用 useCallback;
- 样式类名(如 styles.selectedStateContainer)需在 CSS 模块中正确定义,否则视觉不可见。
通过以上调整,用户选择州后,对应地点信息将立即、稳定、可维护地渲染出来。










