【问题标题】:unable to set state after get request获取请求后无法设置状态
【发布时间】:2026-02-03 06:15:01
【问题描述】:

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

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

【问题讨论】:

  • 为了 setState() 工作,您需要将整个状态存储在一个名为 state 的对象上,您正在尝试更新一个不存在的状态

标签: reactjs express axios


【解决方案1】:

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

可以试试

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 我猜是语法...谢谢