无法将axios数据设置为状态

时间:2019-09-22 21:22:10

标签: reactjs axios

我已经将数据状态初始化为空数组。我正在尝试从axios post方法中获取数据,例如

componentDidMount(){
    var a=this;
    axios.post("http://localhost/axios/index.php")
    .then((res)=>{
      a.setState({datas:res.data});
    });
    console.log(this.state);
}

我收到了

{0: {…}, 1: {…}, 2: {…}, 3: {…}, 4: {…}, 5: {…}}
0: {id: "1", typee: "class", user_id: "1"}
1: {id: "2", typee: "class", user_id: "1"}
2: {id: "3", typee: "course", user_id: "1"}
3: {id: "4", typee: "class", user_id: "2"}
4: {id: "5", typee: "test_series", user_id: "3"}
5: {id: "6", typee: "test_series", user_id: "2"}

如果我console.log(res.data),则此数据 但是如果我使用console.log(this.state),它仍然会给我空数组

1 个答案:

答案 0 :(得分:3)

setState是异步的,因此在控制台对其进行记录时,状态尚未更新。您可以使用setState的回调形式来获取更新状态:

setState(
  { datas:res.data },
  () => console.log(this.state)
);

此处有更多信息:https://reactjs.org/docs/react-component.html#setstate