首页 > 解决方案 > Axios GET请求后反应页面未更新

问题描述

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

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>
    )
}

}

用户应该在主登陆页面(例如伦敦)输入城市名称,然后登陆一个带有 URL 的页面,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 响应中访问数据。我究竟做错了什么?

标签: node.jsreactjsmongodbexpressaxios

解决方案


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

这将帮助您了解您是否至少达到了状态更新的程度。如果不是问题来自 axios 的响应,否则就是您访问数据的方式。

我的猜测是您的 API 的响应是一个数组,所以 this.state.selected_city 必须是一个数组。如果是这样,像 this.state.selected_city.name 这样访问它不会做任何事情


推荐阅读