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

问题描述 投票:-1回答:1

这是我的代码片段:

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获取值,我想在我的planner组件状态中更新响应。它没有反映出来。

有没有新的方法来实现这个?我是新来的反应。

reactjs axios state
1个回答
2
投票

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

  this.setState({
      destinations: data.destinations,
      vacations: data.vacations,
      itineraries: data.itineraries
    });
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.