React setState赋值后state未更新,控制台打印为null问题求助
问题原因
fetch是异步网络请求API,你调用fetch之后,其内部的.then回调不会立刻同步执行,会等到网络请求成功拿到响应数据后才会触发回调执行setState。而你写的console.log(this.state.users)是和fetch调用同级的同步代码,执行时机远早于网络请求返回、setState被调用的时机,此时users还是初始值null。- 哪怕你把
console.log写在setState调用的下一行,也拿不到最新值。因为React类组件中的setState本身就是异步批量更新的设计,调用setState后不会立刻修改this.state的取值,要等React完成状态更新批量处理后才会生效。
解决方法
- 如果你要在
setState执行完成后拿到最新的state值,可以使用setState的第二个回调参数,该回调会在状态更新完成后触发:
componentDidMount() { fetch("https://jsonplaceholder.typicode.com/users") .then((response) => response.json()) .then((data) => this.setState({ users: data }, () => { // 回调内可以拿到更新后的state console.log(this.state.users) }) ) }
- 也可以在
componentDidUpdate生命周期中监听state变化,拿到更新后的值:
componentDidUpdate(prevProps, prevState) { // 避免重复打印,只有users变化时才执行 if (prevState.users !== this.state.users) { console.log('更新后的users:', this.state.users) } }
额外提示
渲染时建议对users做非空判断,避免数据还没加载完成时调用users的属性或方法抛出错误:
render() { const { users } = this.state return ( <div> <h1>Users</h1> {users ? ( <ul> {users.map(user => <li key={user.id}>{user.name}</li>)} </ul> ) : <p>用户数据加载中...</p>} </div> ) }
内容的提问来源于stack exchange,提问作者hotebi
相关产品推荐
相关产品推荐

