首页 > 解决方案 > 根据另一个值过滤元素

问题描述

我想在 ReactJs 中输出每个帖子的所有问题的数量。为此,我创建了下一个代码:

const posts = [{
        title: 1,
        id: "123"
    },
    {
        title: 2,
        id: "1234"
    },
    {
        title: 3,
        id: "12345"
    }
]

const questions = [{
        id: 55,
        name: 'question one',
        id_post: '123'
    },
    {
        id: 56,
        name: 'question two',
        id_post: '123'
    },
    {
        id: 57,
        name: 'question three',
        id_post: '1234'
    },
    {
        id: 58,
        name: 'question four',
        id_post: '123'
    },

];

posts.map( (e, k) => {
    return (
      <Link key={k} to={`demo/${e.id}/url`}>
      { questions.filter(here i want to output the number of questions that correspond to each post)}
      </Link>
    )
})

我有posts数组和questions数组。我想Link在 url 中创建一个带有它自己的 id 的内容,同时过滤每个帖子的问题数量,并在里面Link输出数字。对此怎么办?

...问题是下一个:我正在使用 ant design,table 组件,我可以使用下一个结构:

`  render: ()=>(
    console.log('render'),
    events.map( (e, key) => {
      console.log(ev.id);
        return (
            <Link key={k} to={`demo/${e.id}/url`}>
            { questions.filter(q => q.id_post === e.id).length }
            </Link>
        )
      )
    })

I use this to create a column in my table. The problem is that i have to many renders. When i put this code i get all ids inconsole.log(ev.id) on each render. And at the end i get for example not0 as length but00000000`,取决于我有多少渲染或 id。如何解决这个问题?请看一下:45 https://codesandbox.io/s/8i1dy

标签: javascriptreactjs

解决方案


一种可能的方法是事先进行此计数:

const questionCountByPost = questions.reduce((acc, q) => {
  const postId = q.id_post;
  acc[postId] = (acc[postId] || 0) + 1;
  return acc;
}, {});

...每次您的帖子或问题发生变化时,这看起来都是一件好事。您可以在 map 函数中使用此对象,如下所示:

return (
  <Link key={k} to={`demo/${e.id}/url`}>
  { questionCountByPost[e.id] }
  </Link>
)

另一种方法是直接在模板中进行此计数:

return (
  <Link key={k} to={`demo/${e.id}/url`}>
  { questions.filter(q => q.id_post === e.id).length }
  </Link>
)

它的性能较低(因为您每次都必须遍历整个数组),但显然更具可读性。如果帖子和问题的数量不是那么大,它可能是一个更好的解决方案。


推荐阅读