You need to enable JavaScript to run this app. React报错Cannot read properties of undefined (reading 'map')问题求助
优惠活动
大模型
产品
解决方案
定价
更多

React报错Cannot read properties of undefined (reading 'map')问题求助

问题根因与修复方案

核心错误点

  • useState语法使用错误:React的useState Hook返回值为长度为2的数组,格式为[状态值, 状态更新方法]。你的代码中将其写为数组嵌套对象解构,相当于从空数组的第一个元素(默认是undefined)中提取songs字段,因此初始状态下songs本身就是undefined,调用map方法时自然触发类型错误。
  • 缺少边界判断:未对接口返回的数据做类型校验,若后端返回非数组类型,即使修复了useState语法仍可能触发同类错误。

修复后代码

const { user } = useAuth0();
// 修正useState语法,直接解构返回的数组
const [songs, setSongs] = useState([])

useEffect(() => {
    if (user) {
        const requestOptions = {
            method: 'GET'
        };
        let url = 'https://present-deck.com/getsongs/' + user.sub
        fetch(url, requestOptions)
        .then(response => {
            return response.json();
        }).then(jsonResponse => {
            // 新增类型校验,确保存入state的始终是数组
            setSongs(Array.isArray(jsonResponse) ? jsonResponse : [])
        }).catch (error => {
            console.log(error);
        }) 
    }
}, [user])
return (
    <>
    <ul>
        {/* 新增可选链运算符,songs非有效值时跳过map调用避免报错 */}
        {songs?.map((el) => (
            <li key={el} className="tailwindCssStuff"
            onClick={ () => {if (listedSongs.indexOf(el.title) === -1){
                addListedSongs(listedSongs.concat(el.title))}}}>
            {el.title}</li>
        ))}
    </ul>
    </>
)
}

补充说明

你在useEffect中调用setSongs后直接打印songs,无法拿到最新的状态值,因为React的状态更新是异步操作,更新后的状态需要在下一次组件渲染时才能获取到。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 05:57:04