获取请求后无法设置状态

时间:2019-03-18 18:15:48

标签: reactjs express axios

我正在尝试在获取请求后使用以下数据更改我的状态,但是在设置状态后状态永远不会更改 enter image description here

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

2 个答案:

答案 0 :(得分:0)

您是否尝试过使用set状态回调?当击中console.log时,您的状态可能尚未更新。

也许尝试

this.setState({profileinfo:data[0].firstname}, () => console.log(this.state.profileinfo))

答案 1 :(得分:0)

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