javascript - 尝试在 REACT 页面上呈现数据库中的数据

标签 javascript reactjs axios

我终于没有收到任何错误,但现在我无法从数据库中获取数据以在页面上呈现

这是问题所在:

import React, { Component } from 'react';
import axios from 'axios';

export default class ListPets extends Component {

    constructor(props) {
        super(props);

        this.state = {
            pets: {},
            isLoaded: false,
        }  
    }

    componentDidMount = () => {
        This. getPets ();
    };

    getPets = async () => {  
        const res = await axios.get('http://localhost:5000/pets');
        const pets = res.data;
        this.setState({ isLoaded: true, pets });
        console.log('Data has been received!');
    }

    render() {
        console.log('State: ', this.state);

        const { isLoaded, pets  } = this.state;

        if (!isLoaded) {
            return <div>Loading...</div>;
        } else {

            return (
                <div>
                    <ul>
                        {Object.entries(pets).map(([key, pet]) => ( 
                             <li key={key}>{pet.name}</li>
                        ))}
                    </ul>
                </div>
            );
        }
    }
}

这是我尝试从数据库呈现的数据


{
    "_id": "5dfe7b55a3678700785c9b69",
    "species": "Collie",
    "name": "Dax",
    "age": "2",
    "petImage": "C:\\fakepath\\brown-and-white-dog-4633734_640.jpg"
}
{
    "_id": "5dfe828af33fa800ac8b49c8",
    "species": "lab",
    "name": "bea",
    "age": "1",
    "petImage": "C:\\fakepath\\puppy-1207816_640.jpg"
}
{
    "_id": "5dfea025ea5cc2016e528f5a",
    "species": "pittbull",
    "name": "nina",
    "age": "3",
    "petImage": "C:\\fakepath\\pitbull1.jpg"
}
{
    "_id": "5dfea0c229d0d4017b982f35",
    "species": "pittbull",
    "name": "nina",
    "age": "3",
    "petImage": "C:\\fakepath\\pitbull1.jpg"
}
{
    "_id": "5dfea63eb1505e018a2ba363",
    "species": "pittbull",
    "name": "Gina",
    "age": "3",
    "petImage": "C:\\fakepath\\pitbull1.jpg"
}
{
    "_id": "5dfea7a1fed64001b9632b8f",
    "species": "pittbull",
    "name": "kat",
    "age": "2",
    "petImage": "C:\\fakepath\\pitbull1.jpg"
}

最佳答案

如果您要获取数据,请使用状态

 return (
                <div>
                    <ul>
                        {this.state.pets.map(pet => ( 
                             <li key={pet.id}>{pet.name}</li>
                        ))}
                    </ul>
                </div>
            );
        }
    }
}


关于javascript - 尝试在 REACT 页面上呈现数据库中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59706474/

相关文章:

javascript - phonegap 离线/在线事件不工作

javascript - 循环div?

javascript - 为什么用 Node.js 运行 Mocha 第一次可以,但第二次不行?

javascript - Next.js:未定义窗口

javascript - 在 Heroku 部署后,React 客户端在指定本地主机时因 Axios 而失败

javascript - 单击 href 更新 iFrame src

javascript - 使用 ref 在 React 中创建单选按钮

javascript - 如何在React应用程序中从数据库获取并显示图像

vue.js - 使用 axios 将文件发布到谷歌存储桶

node.js - 如何从服务器下载文件,然后将其再次发布到另一服务器中 (Node.js)