从模板中的自定义帖子类型中仅拉取一个类别,可以通过以下步骤实现:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const CustomPost = () => {
const [posts, setPosts] = useState([]);
const [selectedCategory, setSelectedCategory] = useState('');
useEffect(() => {
fetchPosts();
}, []);
const fetchPosts = async () => {
try {
const response = await axios.get('/api/posts'); // 替换为实际的后端接口地址
setPosts(response.data);
} catch (error) {
console.error(error);
}
};
const handleCategoryChange = (event) => {
setSelectedCategory(event.target.value);
};
const filteredPosts = posts.filter((post) => post.category === selectedCategory);
return (
<div>
<select value={selectedCategory} onChange={handleCategoryChange}>
<option value="">All Categories</option>
<option value="category1">Category 1</option>
<option value="category2">Category 2</option>
<option value="category3">Category 3</option>
</select>
<ul>
{filteredPosts.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
);
};
export default CustomPost;
上述代码中,我们首先使用useState来定义了两个状态变量:posts
用于存储所有帖子数据,selectedCategory
用于存储用户选择的类别。
在组件渲染时,通过useEffect
钩子调用fetchPosts
函数来获取所有帖子数据,并将其存储在posts
状态变量中。
在handleCategoryChange
函数中,我们通过event.target.value
获取用户选择的类别,并将其存储在selectedCategory
状态变量中。
然后,我们使用filter
方法对posts
数组进行过滤,只保留类别与selectedCategory
相匹配的帖子。
最后,我们在渲染部分使用<select>
元素来展示类别选择的下拉列表,并根据filteredPosts
数组渲染相应的帖子列表。
这只是一个简单的示例,实际情况中可能需要根据具体的需求进行适当的修改和调整。
对于腾讯云相关产品,推荐使用腾讯云的云服务器(CVM)来搭建后端服务,使用腾讯云对象存储(COS)来存储帖子数据,使用腾讯云数据库(TencentDB)来存储帖子的类别信息。具体产品介绍和链接如下:
请注意,以上只是推荐的腾讯云产品,实际选择应根据具体需求和项目要求进行评估和决策。
领取专属 10元无门槛券
手把手带您无忧上云