首页 > 解决方案 > 获取请求后无法设置状态

问题描述

我试图在获取请求后使用以下数据更改我的状态,但在设置状态后状态永远不会改变 在此处输入图像描述

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)
    }   

标签: reactjsexpressaxios

解决方案


我认为这是一种语法。您需要在.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是一个异步函数。


推荐阅读