本文解决使用 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)}
);
}
✅ 关键改进说明: