我想输出 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>
)
})
I have 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 in
控制台.log(ev.id)on each render. And at the end i get for example not
0as length but
00000000`,取决于我有多少个渲染或 ID。怎么解决这个问题呢?请看一下这一行:45https://codesandbox.io/s/8i1dy https://codesandbox.io/s/8i1dy
一种可能的方法是预先进行此计数:
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>
)
它的性能较差(因为您每次都必须遍历整个数组),但显然更具可读性。如果帖子和问题的数量不是那么大,这可能是一个更好的解决方案。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)