解决axios请求后组件状态未更新

时间:2019-03-26 10:41:58

标签: reactjs axios state

这是我的代码段:

import React, { Component } from "react";
import axios from "axios";
import PlanDetails from "./PlanDetails";
import Pagination from "./Pagination";
import PropTypes from "prop-types"; //ES6

class Planner extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      destinations: [],
      vacations: [],
      itineraries: []
    };
  }

  componentDidMount() {
    const self = this;
    axios
      .get("sample.json")
      .then(res => {
        const data = res.data;
        self.setState(data => {
          destinations: data.destinations;
          vacations: data.vacations;
          itineraries: data.itineraries;
        });
      })
      .catch(err => {});
  }

  render() {
    return (
      <div>
        <h1>Planner</h1>
        <PlanDetails />
        <Pagination />

        <ul>
          {this.state.destinations.map(destination => (
            <li key={destination.url}>{destination.text}</li>
          ))}
        </ul>
      </div>
    );
  }
}

Planner.propTypes = {};

export default Planner;

在上面的示例中,我尝试在axios的帮助下从本地JSON获取值,并且我想在计划器组件的状态下更新响应。它没有反映出来。

是否有实现此目的的新方法?我是新来的。

1 个答案:

答案 0 :(得分:2)

setState语法在您的代码中不正确。另外,您不需要self,因为您将箭头函数用于axios .then回调,它将把上下文绑定到封闭范围

  this.setState({
      destinations: data.destinations,
      vacations: data.vacations,
      itineraries: data.itineraries
    });