reactjs - 设置新后状态未更新
问题描述
我是新来的反应并面临问题。我正在使用 Axios 从 API 获取数据,然后我必须将该数据设置为状态并将该值作为道具传递到另一个组件中。我的问题是我this.setState
在获取 API 后使用更改状态,但状态没有改变。所以我在下面分享我的代码。
constructor(props){
super(props);
this.state={
employeeData:[] // setting empty value
}
}
ComponentDidMount(){
console.log("Current State"+JSON.stringify(this.state)) ///output = []
axios.get("http://localhost:8080/hris/api/employee/get/all")
/// getting values , can see them in network
.then(response => response.data)
.then((data) => {
this.setState({ employeeData: data }) ///setting new value
console.log(this.state.employeeData) /// can see fetched data
})
.catch(err=> console.log(err))
console.log("2Nd STATE "+this.state) /// again empty state, there is no fetched data
}
然后我必须在另一个组件中传递该状态。
render(){
return(
<div className=" col-md-12" style={viewData}>
<div >
<p><b>All Employee Details</b></p>
</div>
<Table data={this.state.employeeData}/>
</div>
)
}
解决方案
setState
是异步函数,它需要一些时间来设置新的状态值。所以在这一行之后打印新状态只会给你以前的状态而不是新的状态。
你需要一个回调来检查改变的状态,
this.setState({ employeeData: data }, () => console.log("2Nd STATE "+this.state))
另一件事是,axios旨在减少.then()
. 使用 axios,您将获得直接JSON
价值。您可以删除 1 .then()
。
axios.get("http://localhost:8080/hris/api/employee/get/all") /// getting values , can see them in network
.then(response => {
this.setState({ employeeData: response.data }, () => console.log("2Nd STATE "+this.state)) // This will give you new state value. Also make sure your data is in `response.data` it might be just `response`.
console.log(this.state.employeeData) // This will give you previous state only
})
.catch(err=> console.log(err))
推荐阅读
- sas - 使用带有空 BASE 的 PROC APPEND 时定义 BASE 结构
- php - wordpress登录重定向后如何传递GET变量
- python - try..except 在交互式 Windbg Python 会话中让我退出 Python 会话
- django - Django:注释缺失的日期
- javascript - 如何在没有 Nodemon 的情况下构建 Nodejs 应用程序并部署在本地 LAN 网络上
- mysql - MYSQL:获取上一行但基于非主列
- reactjs - 如何在反应js中将默认索引页面更改为登录页面
- maven - 带有一个参数库的 AssertThat
- kubernetes - 将电报作为守护进程运行
- android - 菲律宾的 Cloud Firestore 位置推荐