首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React.js setState函数不分配数据

React.js setState函数不分配数据
EN

Stack Overflow用户
提问于 2019-12-04 02:19:47
回答 1查看 54关注 0票数 0

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

代码语言:javascript
复制
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如下所示:

代码语言:javascript
复制
{
  "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
    }
  ]
}

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

EN

回答 1

Stack Overflow用户

发布于 2019-12-04 02:22:29

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

setState是异步的。

您需要在更新完成后将其记录下来。该方法接受一个回调。

代码语言:javascript
复制
this.setState({ tickets : response.data }, () => console.log(this.state))
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59163146

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档