【问题标题】:Component state not getting updated after axios request is resolved解决 axios 请求后组件状态未更新
【发布时间】:2019-03-26 10:41:58
【问题描述】:

这是我的代码 sn-p:

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 获取值,并且我想更新我的规划器组件状态中的响应。它没有反射。

有什么新方法可以实现吗?我是新手。

【问题讨论】:

  • 您完全是 javascript 新手吗?

标签: reactjs axios state


【解决方案1】:

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

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

【讨论】:

  • 我很确定你应该在setState() 中使用逗号, 而不是分号; :)
猜你喜欢
  • 2020-07-05
  • 2019-03-13
  • 2019-08-09
  • 2019-04-03
  • 1970-01-01
  • 2019-10-01
  • 2021-04-09
  • 2021-06-15
相关资源
最近更新 更多