React类组件fetch后state已设置但访问state.user报undefined错误
核心问题定位
- 初始状态下
user值为null,组件首次渲染时网络请求还未返回,直接访问this.state.user.xxx等价于读取null的属性,直接触发undefined访问报错。你在控制台看到state设置成功的记录,是异步请求完成后state的最终更新结果,但页面在第一次渲染时就已经因为空属性访问崩溃,没有等到数据加载完成 setState是异步批更新机制,代码中刚执行完this.setState({userData: res})就立刻在循环中读取this.state.userData[i],此时state还未完成同步更新,userData依然为初始值null,根本无法遍历数组完成id匹配- 在constructor阶段直接触发异步网络请求,不符合类组件的生命周期执行规则,会导致初始化逻辑和异步加载逻辑脱节
修正方案
调整逻辑时遵循三个规则:
- 把异步数据请求移到
componentDidMount生命周期执行,符合React类组件的加载规范 - 循环匹配用户id时直接使用接口返回的原始数据,不依赖刚设置的state值
- 渲染时做空值兼容处理,在用户数据未加载完成时显示占位提示,避免空属性访问
修正后可运行代码
import { View, Text } from 'react-native' export default class details extends React.Component { constructor(props) { super(props); this.state = { userData: null, user: null, }; } // 异步请求移至组件挂载完成的生命周期执行 componentDidMount() { this.getUsers(); } getUsers = async () => { let urlUsers = "https://jsonplaceholder.typicode.com/users"; let req = await fetch(urlUsers); let res = await req.json(); // 直接使用接口返回的原始数据匹配目标用户,不读取刚设置的state const targetUserId = this.props.route.params.id; const matchedUser = res.find(item => item.id == targetUserId); if (matchedUser) { this.setState({ user: { name: matchedUser.name, uid: matchedUser.id, phone: matchedUser.phone, email: matchedUser.email, website: matchedUser.website, username: matchedUser.username, }, }); } console.log(this.state.user); }; render() { // 空值兼容:用户数据未加载完成时显示占位 if (!this.state.user) { return <View><Text>用户数据加载中...</Text></View> } const user = this.state.user return ( <View> <Text>User Id : {user.uid}</Text> <Text>Name : {user.name}</Text> <Text>email : {user.email}</Text> <Text>phone : {user.phone}</Text> <Text>Website : {user.website}</Text> <Text>username : {user.username}</Text> </View> ); } }
额外优化提示
- 原代码中的手写循环可以用数组
find方法简化,减少冗余逻辑 - 不要给setState加无意义的await,setState本身没有返回Promise,加await不会达到同步更新state的效果
内容的提问来源于stack exchange,提问作者Milan Patel
相关产品推荐
相关产品推荐

