React报错TypeError: Cannot read properties of undefined(reading 'map')原因求解
报错原因分析
这个TypeError: Cannot read properties of undefined(reading 'map') 错误的直接诱因是你尝试对undefined类型的users变量调用map方法,具体问题出在接口数据处理逻辑上:
- 你调用的
https://jsonplaceholder.typicode.com/users接口返回值本身就是用户数组,不存在results字段,你写的setUsers(json.results)会把users状态从初始的空数组改写为undefined,后续渲染时执行users.map就会触发报错。
修复方案
- 修正状态赋值逻辑,直接把接口返回的json赋值给users:
useEffect(() => { fetch(LIST_URL) .then(res => res.json()) .then(json => setUsers(json)) // 移除多余的.results字段 }, [])
- 可选添加渲染兜底逻辑,避免后续其他异常导致users不是数组时再次触发同类型报错:
<ul> {/* 可选链语法会在users为undefined时直接返回undefined,不会执行map触发报错 */} {users?.map(user => ( <li key={user.id}>{user.name}</li> ))} </ul>
- 可以补充加载态、异常态处理逻辑,进一步提升组件健壮性:
const UsersList = () => { const LIST_URL = "https://jsonplaceholder.typicode.com/users " const [users, setUsers] = useState([]) const [loading, setLoading] = useState(true) const [error, setError] = useState(null) useEffect(() => { fetch(LIST_URL) .then(res => res.json()) .then(json => { setUsers(json) setLoading(false) }) .catch(err => { setError(err) setLoading(false) }) }, []) if (loading) return <div>加载中...</div> if (error) return <div>加载失败,请稍后重试</div> return ( <> <header> <h1>My contact list</h1> </header> <section> <ul> {users.map(user => ( <li key={user.id}>{user.name}</li> ))} </ul> </section> </> ) }
内容的提问来源于stack exchange,提问作者dannuzak
相关产品推荐
相关产品推荐

