React.js setState函数不分配数据

时间:2019-12-03 18:19:47

标签: javascript reactjs

我正在尝试使用axios.get()从数据库中获取数据,并且得到了正确的响应,但是当我尝试将数据分配到我的状态时,它似乎并没有改变状态。

import React, { Component, useState, useEffect } from 'react';
import TicketPanel from './TicketPanel';
import { Link } from 'react-router-dom';
import axios from 'axios';

export class Tickets extends Component {

    state = {
        tickets : []
    }

    componentDidMount() {
        axios.get('/issue-tracker/api/ticket/read.php').then(response => (
            this.setState({ tickets : response.data })
        )); 
    }   

我无法为自己的生活弄清楚为什么它没有改变。 get()运行,我返回的变量response.data看起来像:

{
  "data": [
    {
      "id": "1",
      "title": "first issue",
      "description": "this is the first UI issue",
      "author": "rvagle",
      "status": "open",
      "category_id": "1",
      "category_name": "UI",
      "assigned_dev_id": null
    },
    {
      "id": "2",
      "title": "second issue",
      "description": "this is the first FE issue",
      "author": "rvagle",
      "status": "open",
      "category_id": "2",
      "category_name": "Front End",
      "assigned_dev_id": null
    },
    {
      "id": "3",
      "title": "3rd bug",
      "description": "this is the first BE issue",
      "author": "rvagle",
      "status": "open",
      "category_id": "3",
      "category_name": "Backend",
      "assigned_dev_id": null
    },
    {
      "id": "4",
      "title": "bug 4",
      "description": "this is the first config issue",
      "author": "rvagle",
      "status": "open",
      "category_id": "4",
      "category_name": "config",
      "assigned_dev_id": null
    }
  ]
}

但是,如果我以后尝试记录状态,它仍然是空数组。

1 个答案:

答案 0 :(得分:1)

  

但是,如果我以后尝试记录状态,它仍然是空数组

setState是异步的。

您需要在更新完成后对其进行记录。该方法需要回调。

this.setState({ tickets : response.data }, () => console.log(this.state))