使用MUI Autocomplete组件时无法渲染对应元素的问题
问题分析与解决方案
你的renderSelectedStateWithMap函数存在两个核心问题,导致选中州后没有元素渲染:
- 函数内部调用
locations.map()但未返回该map的执行结果,整个函数默认返回undefined,React无法识别并渲染内容。 - 即使匹配到目标州,内层的
state.locations.map()结果也没有传递到外层逻辑,等于白执行。
修正后的代码
import { Autocomplete, TextField } from '@mui/material'; import styles from './styles.module.css'; import { useState } from 'react'; type JSXElement = React.ReactNode; // 建议用更准确的类型替代any 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 = [ { 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, }, ], }, ]; export default function SearchBar() { const [selectedState, setSelectedState] = useState(''); function renderSelectedStateWithMap(stateName): JSXElement { if (!stateName) return null; // 选中为空时不渲染任何内容 // 用find替代map,更高效地定位匹配的州 const matchedState = locations.find(state => state.name === stateName); if (!matchedState) return null; // 未找到对应州时返回空 // 返回渲染的地点列表,注意添加key属性符合React要求 return matchedState.locations.map((location, index) => ( <div key={index} className={styles.selectedStateContainer}> {location.name} </div> )); } return ( <div className={styles.searchBarContainer}> <Autocomplete disablePortal onChange={(event: any, newValue: string | null) => { setSelectedState(newValue || ''); // 处理null情况 }} id="combo-box-demo" options={statesString} sx={{ width: 300 }} renderInput={(params) => ( <TextField {...params} label="Escolha o Estado" /> )} /> {renderSelectedStateWithMap(selectedState)} </div> ); }
关键优化点
- 补充返回逻辑:确保
renderSelectedStateWithMap函数返回渲染元素或null - 高效查找:用
find替代map定位目标州,避免不必要的遍历 - 空值处理:增加选中值为空、未找到对应州时的边界判断
- 合规渲染:给列表元素添加
key属性,符合React列表渲染规范 - 类型优化:将
JSXElement类型改为React.ReactNode,替代模糊的any
内容的提问来源于stack exchange,提问作者Ernanni
相关产品推荐
相关产品推荐

