根据另一个值过滤元素

时间:2020-03-24 08:26:32

标签: javascript reactjs

我想输出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内以输出数量。该怎么做?

...下一个问题是:我正在使用蚂蚁设计,表组件,并且可以在其中使用下一个结构:

`  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 in console.log(ev.id)on each render. And at the end i get for example not 0 as length but 00000000`,具体取决于我拥有多少个渲染器或ID。如何解决呢?请查看以下行:45 https://codesandbox.io/s/8i1dy

2 个答案:

答案 0 :(得分:1)

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

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

...每当您的帖子或问题发生变化时,这似乎都是一件不错的事情。您可以在地图函数中使用此对象,如下所示:

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>
)

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

答案 1 :(得分:0)

color