React Native分类标签筛选帖子代码正确性验证求助
你的前端筛选思路是对的,但有几处细节需要调整
首先,先给你点个赞——既然已经拿到了全部帖子数据,前端做分类筛选确实是更高效的方案,不用再重复调用API,这个方向没问题。不过你更新后的代码还有几个小问题,我帮你梳理下:
1. 冗余/错误的状态操作
你的toggleBrands函数里写了setLabel(label),这里的label是函数作用域里的旧值,而且你已经通过setLabelFilter(e.label)设置了标签文本,这行代码完全多余,直接删掉就好。
2. 初始状态的合理性
当前currentCategoryId的初始值是undefined,这会导致页面刚加载时显示所有帖子,但你默认选中的是Sports标签,应该把初始值设为Sports的id(也就是1),这样初始状态就和选中的标签对应起来:
const [currentCategoryId, setCurrentCategoryId] = useState(1)
3. 选中样式的可靠性
之前你用label===e.label来判断选中状态,虽然当前分类的label都是唯一的,但用id判断更可靠(毕竟后端的categoryId是唯一标识)。所以标签的选中样式应该改成基于currentCategoryId:
<TouchableOpacity style={[ {paddingHorizontal:10,paddingBottom:10}, currentCategoryId === e.id && {borderBottomWidth:3, borderBottomColor:colors.primary, borderRadius:2, } ]} onPress={()=>{toggleBrands(e.id), setLabelFilter(e.label)}} key={e.id} > <AppText style={[{fontWeight:"500",color:colors.medium},currentCategoryId === e.id && {color:colors.primary,fontWeight:"700"}]}> {e.label} </AppText> </TouchableOpacity>
4. 冗余状态清理
初始代码里的dataList状态你完全没用到,直接删掉它,减少不必要的状态维护。
修正后的核心代码片段
把这些调整整合后,关键部分的代码应该是这样的:
// 状态定义 const [label, setLabel] = useState('Sports') const [currentCategoryId, setCurrentCategoryId] = useState(1) // 初始设为Sports的id // 切换分类的函数简化 const toggleCategory = (categoryId, categoryLabel) => { setCurrentCategoryId(categoryId) setLabel(categoryLabel) }; // 分类标签渲染 <ScrollView horizontal style={{flexDirection:"row", alignContent:"center", width:Dimensions.get('window').width/1.05, marginBottom:20, }} showsHorizontalScrollIndicator={false} > {categories.map(e=>( <TouchableOpacity key={e.id} style={[ {paddingHorizontal:10,paddingBottom:10}, currentCategoryId === e.id && {borderBottomWidth:3, borderBottomColor:colors.primary, borderRadius:2, } ]} onPress={()=>toggleCategory(e.id, e.label)} > <AppText style={[{fontWeight:"500",color:colors.medium},currentCategoryId === e.id && {color:colors.primary,fontWeight:"700"}]}> {e.label} </AppText> </TouchableOpacity> ))} </ScrollView> // FlatList的数据源 <FlatList data={currentCategoryId ? posts.filter(post => post.categoryId === currentCategoryId) : posts} keyExtractor={(post) => post.id.toString()} renderItem={({ item,index }) => ( <Card title={item.title} subTitle={item.subTitle} onPress={() => navigation.navigate(routes.POST_DETAILS, {post:item,index})} /> )} />
额外优化建议
为了避免每次渲染都重新执行filter,可以用useMemo缓存筛选后的结果,提升性能:
const filteredPosts = useMemo(() => { if (!currentCategoryId) return posts; return posts.filter(post => post.categoryId === currentCategoryId); }, [posts, currentCategoryId]); // 然后FlatList的data用filteredPosts <FlatList data={filteredPosts} ... />
这样调整后,你的分类筛选功能就能正常工作了,选中对应的标签只会显示该分类下的帖子。
内容的提问来源于stack exchange,提问作者kd12345
相关产品推荐
相关产品推荐

