【问题标题】:ReactJS set state does not assign array from Axios response dataReactJS 设置状态不会从 Axios 响应数据中分配数组
【发布时间】:2020-01-30 13:02:21
【问题描述】:

我在 react 组件构造函数中定义了一个空数组,我希望将它与来自 API 调用的 json 响应数据一起分配

class Grid extends Component {
  constructor(props) {
    super(props);

    this.state = {
      blogs : []
    };
  }

我调用componentDidMount 方法在这个组件上加载数据,我使用setState 来分配值

componentDidMount(){
  Axios.get("/api/blogs").then(response => {
    const blogData = response.data;
    this.setState({blogs: blogData.data});
  });
}

JSON 响应数据如下(Laravel 集合资源与元和链接)

{
  "data": [
    {
      "title": "Experiments in DataOps",
      "status": true,
      "publish_date": "2020-01-29",
      "slug": "experiments-in-dataops"
    },
    {
      "title": "What is it about certifications anyway?",
      "status": true,
      "publish_date": "2020-01-29",
      "slug": "what-is-it-about-certifications-anyway"
    }
  ],
  "links": {
    "self": "link-value",
    "first": "http://adminpanel.test/api/blogs?page=1",
    "last": "http://adminpanel.test/api/blogs?page=1",
    "prev": null,
    "next": null
  },
  "meta": {
    "current_page": 1,
    "from": 1,
    "last_page": 1,
    "path": "http://adminpanel.test/api/blogs",
    "per_page": 15,
    "to": 2,
    "total": 2
  }
}

但是,当我稍后在填充网格数据时调用它时,blogs 数组仍然未定义

<BootstrapTable data={this.blogs} version="4" striped hover pagination search options={this.options}>

我得到一个空表,在 blogsthis.blogs 上调用 console.log 显示它未定义。

我正在为这个网格组件使用reactstrapreact-bootstrap-table

【问题讨论】:

    标签: javascript reactjs laravel axios


    【解决方案1】:

    您没有正确访问state 以访问blogs 使用this.state.blogs

    <BootstrapTable data={this.state.blogs} version="4" striped hover pagination search options={this.options}>
    

    【讨论】:

      猜你喜欢
      • 2021-08-07
      • 1970-01-01
      • 2019-07-04
      • 2020-11-05
      • 1970-01-01
      • 2021-04-27
      • 2019-05-18
      • 2019-01-19
      • 1970-01-01
      相关资源
      最近更新 更多