Axios GET请求后反应页面未更新

时间:2020-09-07 21:30:25

标签: node.js reactjs mongodb express axios

我正在尝试使用Axios将请求发送到后端时创建一个MERN应用程序,但是我无法获取要在页面上呈现的数据。

import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';

export default class City extends Component {
constructor(props){
    super(props);
    this.state = { 
        selected_city: {
            _id: "",
            name: "",
            country: ""
        }
    };
}
//Retrieves the requested city from the back-end to update the page's state.
componentDidMount(){
    let city_name = this.props.match.params.name
    
    axios.get('http://localhost:4000/city/' + city_name)
        .then(response => { 
            console.log("Response: " + response);
            console.log("Data: " + response.data);
            console.log("String version: " + JSON.stringify(response.data));
            console.log("Name: " + response.data.name);
            this.setState({selected_city: response.data});
        })
        .catch(function(error){
            console.log(error);
        })
}
render() {
    return (
        <div className='text-center'>
            <p>Name: {this.state.selected_city.name}</p>
            <p>Description: {this.state.selected_city.country}</p>
        </div>
    )
}

}

用户应在主登录页面(例如伦敦)上输入城市名称,然后登录到网址为localhost:3000/city/<city-name>之类的页面上,并提供一些详细信息。

问题是,数据出现在控制台中,如下所示:

Response: [object Object]
Data: [object Object]
String version: [{"_id":"5f5637ecf06f63e92b39e71d","name":"London","country":"United Kingdom"}]

如果我使用Postman查询端点,那么我还将获得预期的JSON响应。

编辑:我在Axios GET中添加了一个虚拟变量,如下所示:

axios.get('http://localhost:4000/city/' + city_name)
        .then(response => { 
            console.log("Response: " + response);
            var dummy_city = {"_id": "1215144156", "name": "London", "country": "United Kingdom"};
            this.setState({
                selected_city._id: dummy_city._id,
                selected_city.name: dummy_city.name,
                selected_city.country: dummy_city.country
            //this.setState({selected_city: response.data});
        })
        .catch(function(error){
            console.log(error);
        })

...并且出现虚拟数据,但是我仍然没有运气从GET响应中访问数据。我在做什么错了?

1 个答案:

答案 0 :(得分:1)

出于调试目的,您应尝试将状态内容记录在render方法中。 (例如:render()下的console.log(this.state)。)

这将帮助您了解您是否已达到状态更新的地步。如果不是,那么问题出在axios的响应上,否则就是您访问数据的方式。

我的猜测是来自您的API的响应是一个数组,因此this.state.selected_city必须是一个数组。如果是这样,则像this.state.selected_city.name一样访问它