我正在尝试使用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
}
]
}但是,如果我之后尝试记录状态,它仍然是空数组。
发布于 2019-12-04 02:22:29
然而,如果我之后尝试记录状态,它仍然是空数组
setState是异步的。
您需要在更新完成后将其记录下来。该方法接受一个回调。
this.setState({ tickets : response.data }, () => console.log(this.state))https://stackoverflow.com/questions/59163146
复制相似问题