javascript - 根据另一个值过滤元素
问题描述
我想在 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 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
解决方案
一种可能的方法是事先进行此计数:
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>
)
它的性能较低(因为您每次都必须遍历整个数组),但显然更具可读性。如果帖子和问题的数量不是那么大,它可能是一个更好的解决方案。
推荐阅读
- windows - YOLO 训练期间没有生成检查点
- c# - 使用 PowerAPI 的 Win32 互操作 - PowerIsSettingRangeDefined() 是未定义/缺失的函数
- system - 如何构建翻译系统
- php - 验证 php 对象的字段是否为空值的更好方法
- python - Apache Airflow ImportError:无法导入名称'_psutil_linux'
- firebase - 如何在 Firestore 中获取每个用户或客户的帐单详细信息?
- java - netbeans 调试错误 - nbjpdastart 不支持嵌套的“modulepath”元素
- material-ui - material-ui-next 表格超出容器宽度且不可滚动
- python-3.x - 从导入的模块中设置/修改函数中使用的变量
- c - 最适合基于前缀的搜索的数据结构