【问题标题】:How to fetch from backend database to display on frontend using react?如何使用 React 从后端数据库中获取以显示在前端?
【发布时间】:2021-04-01 13:00:30
【问题描述】:

我正在尝试从本地主机上的后端数据库 (MongoDB) 中获取以显示所有博客文章。

我假设我需要遍历前端的每篇博文。目前,仅显示“作者”和“评论”,但没有实际数据。

该语法是什么样的?

这是我正在获取和显示的 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

【问题讨论】:

  • 有什么问题???
  • @RuanDuarte 问题很清楚...作者这边有一个巨大的错误,这在新开发者中很常见。
  • 是的,我试图检查答案,但我必须经过一段时间才能做到这一点。

标签: node.js reactjs mongodb express mongoose


【解决方案1】:

你应该遍历内容,但你只做一次,这也是在数组上:

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

上面的代码是错误的。你需要做的是迭代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>
));

您可能也需要执行相同的操作来获取 cmets。假设 cmets 是对象中的 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>
));

完整代码在这里:

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;

【讨论】:

    【解决方案2】:

    您正在将this.state.blogPost 设置为您从数据库接收到的博客帖子数组。因此,this.state.blogPost.author 将是未定义的,因为数组没有 .author 属性。数组中的项目将具有属性,访问方式如下:this.state.blogPost[0].author 以获取第一篇文章的作者。

    要为数组中的每个项目显示div,您需要在渲染函数中使用.map 循环遍历数组:

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

    编辑:看起来我被打败了!

    【讨论】:

    • 看起来我被打败了! - 这是什么意思? ?
    • @PraveenKumarPurushothaman 这意味着你很快就回答了我的问题,没关系
    • 是的,我知道这是一件友好的事情!哈哈。只是想知道上下文。 ? 等等,你没看到表情符号吗?这个 - “?”
    猜你喜欢
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 2020-07-18
    • 2020-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多