Javascript 根据React中的类别选择更改博客列表
我对我的问题完全一无所知 我有一个按类别显示的博客帖子列表:Javascript 根据React中的类别选择更改博客列表,javascript,reactjs,Javascript,Reactjs,我对我的问题完全一无所知 我有一个按类别显示的博客帖子列表: const Posts = ({ state }) => { const data = state.source.get(state.router.link); const postsPerCategory = getPostsGroupedByCategory(state.source); console.log(postsPerCategory); return ( <> {p
const Posts = ({ state }) => {
const data = state.source.get(state.router.link);
const postsPerCategory = getPostsGroupedByCategory(state.source);
console.log(postsPerCategory);
return (
<>
{postsPerCategory.map(({ posts, category }, index) => {
return (
<button key={index}>
{category.name}
</button>
)
})}
{postsPerCategory.map(({ posts, category }, index) => {
return (
<div key={index}>
<h1>{category.name}</h1>
{posts.map((post, index) => {
return (
<article key={index}>
{console.log(post)}
{post.title.rendered}
</article>
)
})}
</div>
)
})}
</>
)
}
const Posts=({state})=>{
const data=state.source.get(state.router.link);
const postsPerCategory=getPostsGroupedByCategory(state.source);
console.log(postsPerCategory);
返回(
{postsPerCategory.map({posts,category},index)=>{
返回(
{category.name}
)
})}
{postsPerCategory.map({posts,category},index)=>{
返回(
{category.name}
{posts.map((post,index)=>{
返回(
如果数据结构是这样的:
const postsPerCategory=[
{
员额:[],
类别:{id:1,名称:“cat 1”},
}
]
然后,为了按给定类别获取帖子,您可以使用过滤器
const getPostsByCategory=(category\u id)=>{
const found=postsPerCategory.filter(v=>v.category.id==category\u id);
如果(找到的长度>0){
找到返回[0]。发布;
}
返回null;
}
现在在按钮的onClick
中调用此函数
注意:我认为您应该使用React.usemo
来获取类别以提高性能,并且不要总是使用索引作为组件的键,使用类似key={'category\'+c.id}
const categories = React.useMemo(() => postsPerCategory.map(v => {id: v.category.id, name: v.category.name}), [postsPerCategory]);
请共享postpercategory的结构。您需要在数组上放置筛选器以实现此目的。@sgrmhdk我使用该结构进行了更新。我认为应该将其设置在我有另一个组件的位置“我正在尝试使其显示,以便在单击类别按钮时”->当前无任何内容(有意)当点击按钮时发生。你会想附加某种点击处理程序来向前移动。@JakeWorth是的,我只是一个新手,但现在不知道该怎么做。我意识到这是一件基本的事情,但我盯着它看了这么久,我有点脑死亡