React中的TypeError,如何解决它以便输出正确呈现?

我一直在尝试按照本教程讲解如何在React中使用REST API(本教程使用BootStrap):

https://pusher.com/tutorials/consume-restful-api-react

我遇到了一个肯定可以轻松解决的问题,但对于JavaScript和React来说,我一般还是比较陌生。我正在尝试显示我从REST API(在Django中)使用的JSON输出。我已经测试过API,并且可以正常工作,但是我确信问题出在前端。

如何修复此代码以给定格式显示REST API的输出?

The current code gives me a TypeError

TypeError

TypeError: blog is undefined
Blog
src/components/blog.js:6

  3 | const Blog = ({ blog }) => {
  4 |   return (
  5 |     <div>
> 6 |       <center><h1>Blog Post</h1></center>
    | ^  7 |       {blog.map((blg) => (
  8 |         <div class="card">
  9 |           <div class="card-body">

HTML页面中的预期输出

Blog Post
New blog post to test
Test post
RP

App.js

import React from 'react';
import Blog from './components/blog';
import logo from './logo.svg';
import './App.css';

class App extends React.Component {

  state = {
    blogdata: []
  }

  componentDidMount() {
    fetch('http://localhost:8000/v1/blog/1/')
    .then(res => res.json())
    .then((data) => {
      this.setState({ blogdata: data })
    })
    .catch(console.log)
  }


  render () {
    return (
      <Blog blogdata={this.state.blogdata} />
    );
  }
}

export default App;

/src/components/blog.js

import React from 'react'

    const Blog = ({ blog }) => {
      return (
        <div>
          <center><h1>Blog Post</h1></center>
          {blog.map((blg) => (
            <div class="card">
              <div class="card-body">
                <h5 class="card-title">{blg.title}</h5>
                <h6 class="card-subtitle mb-2 text-muted">{blg.content}</h6>
                <p class="card-text">{blg.author}</p>
              </div>
            </div>
          ))}
        </div>
      )
    };

    export default Blog

JSON Post Detail at http://localhost:8000/v1/blog/1/

HTTP 200 OK
Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "id": 1,
    "title": "New blog post to test",
    "content": "Test post",
    "created_at": "2020-05-11T05:41:43.213782Z",
    "updated_at": "2020-05-11T05:41:43.213951Z",
    "author": "RP"
}
评论
  • qqgsd
    qqgsd 回复

    In Blog component you are receiving blog as prop and while using you are passing blogdata

    Update your app.js

     render () {
        return (
          <Blog blog={this.state.blogdata} />
        );
      }