不读取 props 变量属性的原因是什么?

我从 this.props 中删除了这个。但现在本地主机中没有显示任何内容。


我正在尝试写一个博客页面来做出反应。这是我的 blog.js:


import React from 'react'

const Blog=props=>{

    const {title,author,content}=this.props

    return(

        <div>

         <h2>{title}</h2>

              <h5><i>{author}</i></h5>

              <br/>

              <h3>{content}</h3>

                  </div>

    )

}


export default Blog

我的 App.js 如下:


import React,{Component} from 'react';

import Blog from './Blog'

class App extends Component {

    render(){

        const posts=[

            {

                title:'First',

                author:'Anonymous',

                content:'first Post',

            },

            {

                title:'Second',

                author:'Anonymous',

                content:'Second Post',

            },

            {

                title:'third',

                author:'Anonymous',

                content:'Second Post',

            },

        ]

            return (  

                <div className="container">

                    <Blog postData={posts}/>

                </div>

            );

        }


    }


export default App ;

虽然我执行 npm start 没有错误,但在浏览器中它说:


TypeError: Cannot read property 'props' of undefined

Blog

C:/Myfiles/python/Django/djangorest/booklearn/test-cases/src/Blog.js:5

  2 | 

  3 | 

  4 | const Blog=props=>{

> 5 |     const {title,author,content}=this.props

  6 |     return(

  7 |         

  8 |         <div>

我的选择已经不多了。我该如何解决这个问题?


我最近开始使用 reactjs。任何建议将不胜感激。


慕姐8265434
浏览 135回答 2
2回答

紫衣仙女

您正在使用功能组件并props作为参数传入您的函数 ( props =>)。你不需要使用this.propsjust propswill work。您正在传递一个名为“postData”的帖子数组。在您的博客组件中,您需要:import React from 'react'const Blog=props=>{return props.postData.map((post) => {const { title, author, content } = post;return (&nbsp; <div key={title}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<h2>{title}</h2>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <h5><i>{author}</i></h5>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <br/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <h3>{content}</h3>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; );});}export default Blog;

小怪兽爱吃肉

删除this,因为它不是一个类,并且 props 作为函数的第一个参数传递。import React from 'react'const Blog = (props) => {&nbsp; &nbsp; const { title,author,content } = props;&nbsp; &nbsp; return(&nbsp; &nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<h2>{title}</h2>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <h5><i>{author}</i></h5>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <br/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <h3>{content}</h3>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; )}export default Blog
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript