【问题标题】:React page not updating after Axios GET requestAxios GET请求后反应页面未更新
【发布时间】:2020-12-26 06:48:27
【问题描述】:

我正在尝试创建一个 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>
    )
}

}

用户应在主登录页面(例如伦敦)输入城市名称,然后登录到一个带有类似localhost:3000/city/&lt;city-name&gt; 的 URL 的页面,其中仅包含一些关于它的详细信息。

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

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.js reactjs mongodb express axios


    【解决方案1】:

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

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

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

    【讨论】:

    • 原来问题出在我的 ExpressJS 代码上。我使用 Mongoose 访问数据库,并在模型上调用 find(),该模型将结果作为数组返回。它还返回用户输入是名称一部分的任何结果,例如如果用户输入dam,他们会得到amsterdamrotterdam。我通过将find() 替换为findOne() 来解决此问题,所以现在它只发送一个我可以在我的组件页面中访问的 JSON 对象。
    猜你喜欢
    • 1970-01-01
    • 2020-04-06
    • 1970-01-01
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 2020-07-05
    • 2021-04-09
    相关资源
    最近更新 更多