当我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();
}
最佳答案
这是因为 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/