reactjs - 获取请求后无法设置状态
问题描述
我试图在获取请求后使用以下数据更改我的状态,但在设置状态后状态永远不会改变
profileinfo:
{
Firstname:'Jeff ',
Lastname:'Series',
email:'exam.com',
Address:'502B Inner Circle Riverwalk'
}
componentDidMount() {
fetch("http://localhost:3001/login")
.then(response=>response.json()
.then(data=>(
this.setState({profileinfo:data[0].firstname}))))
console.log(this.state.profileinfo)
}
解决方案
我认为这是一种语法。您需要在.then(response=>response.json()
componentDidMount() {
fetch("http://localhost:3001/login")
.then(response=>response.json()) // <-Insert a close bracket here
.then(data=> this.setState({profileinfo:data[0].firstname}, () => console.log(this.state.profileinfo)) // <- Call console in callback
) // <- Remove one here
console.log(this.state.profileinfo)
}
并在回调函数中调用控制台以获取正确的值。因为setState
是一个异步函数。
推荐阅读
- java - 在 android studio 中创建列表但不断收到此错误“适配器视图是抽象的,无法启动”
- linux - 如何在非 android 项目中使用 Kotlinc 协程?
- python - 查询 Python 中的局部变量和全局变量
- jquery - 重力表单默认验证错误消息显示后自定义 jQuery 未触发/工作
- objective-c - Objective-c 中的 id 类,为什么它适用于任何类?
- android - 如何获得当前的纬度和经度?
- flutter-layout - 如何使用 Flutter 使可滚动图像居中?
- php - SQL:仅基于主键列将缺少的行从一个表复制到另一个表
- angular - 如何在 mat-table 中获取自定义组件的值/内容?
- c# - UWP 打印需要扩展到多页的长数据网格