首次使用MUI复用组件遇TypeError: props.names.map is not a function求助
解决TypeError: props.names.map is not a function的问题
问题原因
- 接口返回的是数组格式数据,但你用了
response.text()解析,这会把数组转换成字符串类型。字符串没有map方法,导致SelectSensor组件调用props.names.map时触发错误。 - 初始状态
sensors是数组,但接口请求完成后,字符串被赋值给sensors,使得传递给组件的names变成了非数组类型。
解决方案
- 修正数据解析方式
将response.text()替换为response.json(),因为接口返回的是JSON数组,response.json()会直接把它解析为JavaScript数组:
const fetchSensors = async () => { const response = await fetch('/api/sensorsRoute/names') const sensorsArray = await response.json() if (response.ok){ setSensors(sensorsArray) } }
- 添加组件边界防护
在SelectSensor组件中,先判断props.names是否为数组再执行map,避免异常情况:
{Array.isArray(props.names) && props.names.map((name) => ( <MenuItem key={name} value={name} style={getStyles(name, personName, theme)} > {name} </MenuItem> ))}
- 添加加载状态提示(可选)
在Query组件中,当数据未加载完成时显示加载提示:
return ( <div className="query"> {sensors.length === 0 ? <div>加载中...</div> : <SelectSensor names={sensors}/>} </div> )
内容的提问来源于stack exchange,提问作者Ruo
相关产品推荐
相关产品推荐

