【问题标题】:how to pass certain id to component using array method in react?如何在反应中使用数组方法将某些 id 传递给组件?
【发布时间】:2022-12-17 14:42:24
【问题描述】:

我想传递与特定 ID 匹配的帖子。我怎样才能返回满足我的条件的某些组件。条件将返回 Post 组件 if (post._id===user.id)

 post?.filter((post, id) => {
   return <Post key={id} data={post} id={id} location='profilepage' handleDelete={handleDelete} />
  })

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:
    const filteredPost = posts.filter((post) => post.id === user.id));
    

    现在使用 filteredPost 你可以映射组件

    【讨论】:

      【解决方案2】:

      filter 方法不会更改数组中的元素,它只是根据条件返回包含或不包含某些元素的相同数组。您想要的是映射您的 post 变量并为每个 post 数据返回一个帖子。

      那就是解释:

      // I renamed post in posts just to clarify the code
      posts?.map((post, id) =>
          post._id === user.id
              ? <Post key={id} data={post} id={id} location="profilepage" handleDelete={handleDelete} />
              : null // If you return null React won't show it
      )
      

      【讨论】:

        【解决方案3】:

        这是 filterincludes 的一个很好的用例:

        const posts = [
        {id: 1, name: "first"},
        {id: 2, name: "second"},
        {id: 3, name: "third post"}
        ]
        
        const wantedPostIds = [1, 3]
        
        console.log(posts.filter(post => wantedPostIds.includes(post.id)))

        【讨论】:

          猜你喜欢
          • 2018-11-16
          • 2019-01-02
          • 2018-11-01
          • 2021-06-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-04-11
          • 2021-10-23
          相关资源
          最近更新 更多