ReactJS中Uncaught TypeError: getOptionLabel非函数问题求助
解决Material UI Autocomplete的getOptionLabel类型错误
错误原因分析
- getOptionLabel参数类型错误:你把
getOptionLabel赋值为subLocationData.map(option => option),这会返回一个数组,但Autocomplete要求getOptionLabel必须是接收单个option参数并返回字符串的函数,这直接触发了TypeError: getOptionLabel Prop is not a function。 - options格式不匹配:你的
subLocationData是包含单个对象的数组([{0:"Intent1", 1:"Intent2", 2:"Intent3"}]),Autocomplete的options需要是可遍历的项数组(比如字符串数组、结构化对象数组),当前格式无法被组件正确解析。
修复步骤
1. 转换数据源格式
先把subLocationData转换为标准的字符串数组:
// 提取对象中的值,转换为字符串数组 const formattedOptions = Object.values(subLocationData[0]);
如果API返回的是动态数据,确保每次获取后都做这个转换。
2. 修正getOptionLabel属性
将getOptionLabel改为符合要求的函数:
getOptionLabel={(option) => option}
因为现在options是字符串数组,直接返回option即可;如果后续用对象数组,这里要返回对象中对应显示的字段(比如option.name)。
3. 调整其他关联逻辑
确保selectedNames的状态与新的options格式匹配,同时简化onChange逻辑。
完整修复后的代码
import { useState } from 'react'; import { Autocomplete, Chip, TextField } from '@mui/material'; // Initialize useState const [selectedNames, setSelectedNames] = useState([]); // 原始数据源 const subLocationData = [{ 0: "Intent1", 1: "Intent2", 2: "Intent3" }]; // 转换为标准字符串数组 const formattedOptions = Object.values(subLocationData[0]); // 渲染组件 return ( <Autocomplete multiple id="fixed-tags-demo" value={selectedNames} onChange={(event, newValue) => { // 直接更新选中值,过滤空值的逻辑可根据需求保留 setSelectedNames(newValue.filter(option => option)); }} options={formattedOptions} getOptionLabel={(option) => option} renderTags={(tagValue, getTagProps) => tagValue.map((option, index) => ( <Chip label={option} {...getTagProps({ index })} /> )) } style={{ width: 500 }} renderInput={(params) => ( <TextField {...params} label={formData.location.value} placeholder={formData.location.value} /> )} /> );
额外注意事项
- 如果API返回的数据源结构可能变化(比如数组长度不止1),可以用
subLocationData.flatMap(item => Object.values(item))来处理多个对象的情况。 - 若后续需要使用结构化对象作为options(比如每个项包含id和name),要同步调整
getOptionLabel为(option) => option.name,并确保selectedNames存储的是对应的对象。
内容的提问来源于stack exchange,提问作者Neha Raghuvanahi
相关产品推荐
相关产品推荐

