简体   繁体   English

如何使用 React 从后端数据库中获取以显示在前端?

[英]How to fetch from backend database to display on frontend using react?

I'm trying to fetch from my backend database (MongoDB) on my localhost to display all blogposts.我正在尝试从本地主机上的后端数据库(MongoDB)中获取以显示所有博客文章。

I'm assuming I need to iterate through each blogpost on the frontend.我假设我需要遍历前端的每篇博文。 Right now, only "Author" and "Comments" display, but with no actual data.目前,仅显示“作者”和“评论”,但没有实际数据。

What would that syntax look like?该语法会是什么样子?

Here's what the React page looks like where I'm fetching and displaying.这是我正在获取和显示的 React 页面的样子。

import React, { Component } from 'react'

class Blog extends Component {
    constructor() {
        super()
    
        this.state = {
          blogPost: [],
          finishedLoading: true
        }
      }    
    
    async componentDidMount() {    
        const response = await fetch('http://localhost:8000/api/blogPosts/all')
        const json = await response.json()
        this.setState({ blogPost: json.blogPosts, finishedLoading: false })
      }
    
    reload = async () => {
        const response = await fetch('http://localhost:8000/api/blogPosts/all')
        const json = await response.json()
        this.setState({ blogPost: json.blogPosts, finishedLoading: true })
      }
    
    render() {
        
    if (this.state.blogPost.length === 0) {
        return (
          <div className="App">
            <h1>No blogposts have been posted!</h1>
          </div>
        )
    }
   

    return (
            <div class="blogPost">
                <h2>{this.state.blogPost.title}</h2>
                <p> Author: {this.state.blogPost.author}</p>
                <p>{this.state.blogPost.content}</p>
                <p>Comments:</p>

                <ul>
                
                </ul>
            </div>
        )
    }
}

export default Blog

You're supposed to iterate through the contents but you're doing only once, that too on an array:您应该遍历内容,但您只做一次,这也是在数组上:

return (
  <div class="blogPost">
    <h2>{this.state.blogPost.title}</h2>
    <p> Author: {this.state.blogPost.author}</p>
    <p>{this.state.blogPost.content}</p>
    <p>Comments:</p>

    <ul></ul>
  </div>
);

The above code is wrong.上面的代码是错误的。 What you need to do is iterate the contents of this.state.blogPost , which is an array of blog objects :您需要做的是迭代this.state.blogPost的内容,这是一个blog对象数组

return this.state.blogPost.map((blog, key) => (
  <div class="blogPost" key={key}>
    <h2>{blog.title}</h2>
    <p> Author: {blog.author}</p>
    <p>{blog.content}</p>
    <p>Comments:</p>
    <ul></ul>
  </div>
));

You might need to do the same thing to fetch the comments too.您可能也需要做同样的事情来获取评论。 Say, the comments are an array of comments in the object, then do this:说,评论是object中的comments数组,然后这样做:

return this.state.blogPost.map((blog, key) => (
  <div class="blogPost" key={key}>
    <h2>{blog.title}</h2>
    <p> Author: {blog.author}</p>
    <p>{blog.content}</p>
    <p>Comments:</p>
    <ul>
      {blog.comments.length > 0 ? (
        blog.comments.map((c, k) => <li key={key}>{c}</li>)
      ) : (
        <li>No comments.</li>
      )}
    </ul>
  </div>
));

Full code here:完整代码在这里:

import React, { Component } from "react";

class Blog extends Component {
  constructor() {
    super();

    this.state = {
      blogPost: [],
      finishedLoading: true
    };
  }

  async componentDidMount() {
    const response = await fetch("http://localhost:8000/api/blogPosts/all");
    const json = await response.json();
    this.setState({ blogPost: json.blogPosts, finishedLoading: false });
  }

  reload = async () => {
    const response = await fetch("http://localhost:8000/api/blogPosts/all");
    const json = await response.json();
    this.setState({ blogPost: json.blogPosts, finishedLoading: true });
  };

  render() {
    if (this.state.blogPost.length === 0) {
      return (
        <div className="App">
          <h1>No blogposts have been posted!</h1>
        </div>
      );
    }

    return this.state.blogPost.map((blog, key) => (
      <div class="blogPost" key={key}>
        <h2>{blog.title}</h2>
        <p> Author: {blog.author}</p>
        <p>{blog.content}</p>
        <p>Comments:</p>
        <ul>
          {blog.comments.length > 0 ? (
            blog.comments.map((c, k) => <li key={key}>{c}</li>)
          ) : (
            <li>No comments.</li>
          )}
        </ul>
      </div>
    ));
  }
}

export default Blog;

You are setting this.state.blogPost to an array of blogPosts that you receive from your database.您正在将this.state.blogPost设置为您从数据库接收的 blogPosts 数组。 So, this.state.blogPost.author will be undefined since an array won't have a .author property.因此, this.state.blogPost.author将是未定义的,因为数组没有.author属性。 The items inside the array will have the property instead, accessed like so: this.state.blogPost[0].author to get the author of the first post.数组中的项目将具有属性,访问方式如下: this.state.blogPost[0].author以获取第一篇文章的作者。

To display a div for every item in the array, you need to loop through the array in your render function with .map :要为数组中的每个项目显示一个div ,您需要使用.map在渲染 function 中循环遍历数组:

return (
        this.state.blogPost.map((post, index) => (
            <div class="blogPost" key={index}>
                <h2>{post.title}</h2>
                <p> Author: {post.author}</p>
                <p>{post.content}</p>
                <p>Comments:</p>
                
                <ul>
                
                </ul>
            </div>
        ));
        
    )

Edit: looks like I was beat to the punch!编辑:看起来我被打败了!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从快速后端服务器获取图像并将其显示到 React Native 前端? - How to Fetch and Display an Image from an express backend server to a React Native frontend? 如何从快速后端服务器获取图像并将其显示到 React js 前端? - How to Fetch and Display an Image from an express backend server to a React js frontend? 如何显示来自 express 后端的错误消息以响应前端? - How to display error message from express backend to react frontend? 通过使用节点作为后端并作为前端反应以什么方式将数据库表显示到材料ui表 - in what way display database table to material ui table by using node as backend and react as frontend 无法从 Nodejs 后端获取数据到 React 前端 - Cannot fetch data from Nodejs backend to React frontend 无法从前端获取后端 - Unable to Fetch backend from frontend 如何从后端(nodejs)重定向到前端(react)? - How to redirect from backend (nodejs) to frontend (react)? 从后端文件夹获取图像并在前端显示(React 和 Node) - Get image from Backend folder and display it in frontend (React and Node) 如何使用Fetch在前端获取后端错误消息 - How to get a backend error message on the frontend using Fetch 如何从后端获取数据到前端? - How do i fetch data from the backend to the frontend?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM