首页 > 解决方案 > 设置新后状态未更新

问题描述

我是新来的反应并面临问题。我正在使用 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>

        )
    }

标签: reactjs

解决方案


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

推荐阅读