React TypeScript用map渲染列表报Cannot read properties of undefined错误如何解决
报错原因与解决方案
核心报错原因
你遇到的TypeError: Cannot read properties of undefined (reading 'map')错误,本质是调用map方法的users变量值为undefined,具体触发原因来自代码的3个疏漏:
users状态没有设置初始值:useState<Array<User>>()未传入初始值,导致users初始状态就是undefined- 缺少
loading状态的初始化逻辑:你贴出的useAllUsers代码中没有声明loading的初始化逻辑,如果loading初始值为false,页面首次渲染会直接跳过加载动画,执行users.map逻辑,此时接口请求还未返回,users仍为undefined - 错误回调逻辑无效:axios的
catch回调中返回<MessageError />不会生效,接口请求失败时users始终为undefined,且finally会把loading设为false,同样会触发报错
修复步骤
- 给
users设置初始空数组,同时补全loading的初始值
修改useAllUsers的状态声明部分:
export const useAllUsers = () => { // 新增loading初始值为true,users初始值为空数组 const [loading, setLoading] = useState(true) const [users, setUsers] = useState<Array<User>>([]) const getUsers = useCallback(() => { axios .get<Array<User>>('https://jsonplaceholder.typicode.com/users') .then(res => { setUsers(res.data) }) .catch(() => { // 请求失败时也给users赋值为空数组,避免undefined setUsers([]) // 此处如果需要展示错误提示,可以新增一个error状态存储信息,不要直接返回组件 }) .finally(()=>{ setLoading(false) }) }, []) return { getUsers, loading, users } }
- 给遍历逻辑增加可选链兜底,双重避免报错
修改users.map的调用部分:
{users?.map(user => ( <UserCard key={user.id} userName={user.username} imageUrl='https://source.unsplash.com/random' userId={user.name} /> ))}
- 可选优化:你定义的
User类型和jsonplaceholder实际返回的字段不一致,返回数据中不存在hobbies字段,建议同步修改类型定义避免后续TS类型报错。
内容的提问来源于stack exchange,提问作者Chi
相关产品推荐
相关产品推荐

