React组件未正确加载

时间:2019-06-14 12:22:25

标签: html css reactjs axios

我正在尝试构建一个单页面的React应用,该应用使用axios从API加载内容。

我已经创建了一个名为“ Importapi”的组件,并在App.js文件中对其进行了调用,但仍未显示任何内容。

有人知道为什么会这样吗?

Importapi-导入组件

import React, { Component } from 'react';
import axios from "axios";
import "./index.css";

export class Importapi extends Component {

    constructor() {
        super();
        this.state = {
            trails: [],
        }
        //this.handleSubmit = this.handleSubmit.bind(this);
    };



    componentDidMount() {
        axios.get("https://www.hikingproject.com/data/get-trails?lat=46.589519&lon=7.912295&maxDistance=100&maxResults=15&key=200490043-7294b2e6976c168d4e44877bf48ef553")
            .then(response => {
                console.log(response.data);
            })
            .catch(error => {
                console.log(error);
            });
    }





    render() {
        return (

            <div className="container2">
                <div className="container1">
                    {this.state.trails}
                </div>
            </div>
        )
    };

};

export default Importapi;

App.js-单页React App

import React from 'react';
import logo from './logo.png';
import './App.css';
import Import from './import.js';
import Importapi from './axios-api'

function App() {
  return (
    <div className="App">
        <header>
            <title>Hikeero</title>
        </header>

        <nav>
            <div className="nav-bar logo">
                <button><a href ="/">BACK</a></button>
            </div>
            <div className="nav-bar items">
            </div>

            <button> <a href="/"> HOME </a> </button>
        </nav>

        <div align="right" >
            <br/>
        </div>

        <h1>Hikeero.</h1>


        <Import />
        <Importapi />


      <header className="App-header">
        <a
          className="App-link"
          href="/import.js/"
          target="_blank"
          rel="noopener noreferrer"
        >
            <br/>
            <br/>
            <br/>
          Click to Start
        </a>

      </header>

    </div>

  );
}

export default App;

没有错误,只是没有显示api信息。

1 个答案:

答案 0 :(得分:0)

您必须在console.log(response.data)下面执行this.setState({Trails:response.data});以显示组件上的内容。这样,API响应将被设置为带有跟踪键名的状态。

componentDidMount() {
        axios.get("https://www.hikingproject.com/data/get-trails?lat=46.589519&lon=7.912295&maxDistance=100&maxResults=15&key=200490043-7294b2e6976c168d4e44877bf48ef553")
            .then(response => {
                // here once you receive response 
                // put the response data into state of the component 
                // as written below
                this.setState({trails: response.data})
            })
            .catch(error => {
                console.log(error);
            });
    }