node.js - 尝试在reactjs中使用GET将状态设置为一个值,

标签 node.js reactjs

当我console.log它时,该值是未定义的。尝试根据非 null 值的状态获取数据,dashboardID 值应为 1,但其未定义,为什么?

getDashboardID = _ => {
    fetch(`http://ca-fpscfb2:4000/dashboardID?name=${this.state.Dashboard}`)
    .then(res => res.json())
    .then(res => { 
      this.setState({ dashboardID: res.dashboardID }, () => {
        console.log(this.state.dashboardID)
      })
     })


} 

handleChangeDashboard = (Dashboard) => {
    this.setState({ Dashboard: Dashboard.value });
    this.getDashboardID();

  }

enter image description here enter image description here enter image description here

最佳答案

这是因为 this.setState 是异步的,并且您的响应是一个对象数组。

因此,您可以使用回调函数访问该值,并确保获得数组响应中的第一项:

// It's array, so access the first result `res[0].dashboardID`
this.setState({ dashboardID: res[0].dashboardID }, () => {
  console.log(this.state.dashboardID)
})

由于异步行为,您也必须应用 handleChangeDashboard 方法。请查看@Solo's answer了解详情。

请查看setState documentation ,了解更多详情

关于node.js - 尝试在reactjs中使用GET将状态设置为一个值,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53504763/

相关文章:

node.js - 将 Mocha 中的对象与 MongoDb 中的日期进行比较

javascript - nwjs下载文件时如何显示进度条

node.js - 在expect().toBe()上应用toBeA()方法时,它会给出一个错误,无法读取未定义的属性

mysql - 如何使用mysql包从nodejs获取结果?

javascript - 避免递归函数中的状态突变(Redux)

reactjs - 目前没有配置加载器来处理这个文件

javascript - Node js 的 npm 操纵杆问题

javascript - 在 React render 方法中使用 for failed inside return 语句

reactjs - react : Need to call parent to re-render component

javascript - 如何调用其他组件中定义的方法