You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

首次使用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变成了非数组类型。

解决方案

  1. 修正数据解析方式
    将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) 
    }
}
  1. 添加组件边界防护
    在SelectSensor组件中,先判断props.names是否为数组再执行map,避免异常情况:
{Array.isArray(props.names) && props.names.map((name) => (
    <MenuItem
        key={name}
        value={name}
        style={getStyles(name, personName, theme)}
    >
        {name}
    </MenuItem>
))}
  1. 添加加载状态提示(可选)
    在Query组件中,当数据未加载完成时显示加载提示:
return (
    <div className="query">
        {sensors.length === 0 ? <div>加载中...</div> : <SelectSensor names={sensors}/>}
    </div>
)

内容的提问来源于stack exchange,提问作者Ruo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 19:57:33