【问题标题】:keep getting an error saying "cannot read properties of null map"不断收到错误消息“无法读取空映射的属性”
【发布时间】:2021-12-11 15:19:13
【问题描述】:
import Post from "./Post"

const PostList = ({posts}) => {


const postComponents = posts.map(post => {
    return (
        <Post
        id = {post.id}
        hub_id={post.hub_id}
        post_body={post.post_body}

         />
    )})


return(
    <div className="postList">
    {postComponents}
    <p>hello world: postList</p>
    </div>
)
}
export default PostList;

【问题讨论】:

  • 这是我的主页.js
  • 您如何使用PostList?看起来posts 为空。

标签: reactjs dictionary


【解决方案1】:

尝试使用 (props) 代替 ({posts}),然后使用 props.posts.map。 在您的代码中,您的帖子为 null 意味着 您的组件没有从 props 获取任何帖子。 有时我不知道是否每个人都会发生这种情况,我的道具没有正确销毁,所以我使用简单的方法。

【讨论】:

    【解决方案2】:
    const postComponents = posts.map(post => {
        return (
            <Post
            id = {post.id}
            hub_id={post.hub_id}
            post_body={post.post_body}
    
             />
        )})
    

    我会把这个 postComponents 改成这个。

    const postComponent = ({posts}) => {
        
     return (
       <div>
           {posts.map((post) => (
                <Post
                key={post.id} // need a key when mapping
                id = {post.id}
                hub_id={post.hub_id}
                post_body={post.post_body}
             />
           ))}
       </div>
     )
    }
    

    当映射任何数组时,您需要将其包裹在另一个元素中,并为每个映射的元素提供一个键。如果将 postComponent 传递给属性帖子,这就是我将如何编写它。您收到的错误可能是因为您没有将帖子传递给您的 postlist 组件。 posts = null //nothing is in posts。我也会把这个 postComponents 分解成另一个文件。

    【讨论】:

      猜你喜欢
      • 2019-04-27
      • 1970-01-01
      • 1970-01-01
      • 2019-11-09
      • 1970-01-01
      • 2021-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多