如何按category属性拆分数组以适配React Native SectionList?
解决React Native SectionList的分类数据结构转换问题
直接从原始产品数组生成目标结构
如果你的原始产品数组是类似这样的:
const products = [ { id: 1, category: 'category1', name: '产品1' }, { id: 2, category: 'category1', name: '产品2' }, { id: 3, category: 'category2', name: '产品3' }, { id: 4, category: 'category2', name: '产品4' }, { id: 5, category: 'category3', name: '产品5' } ];
可以用reduce先按分类分组,再转成SectionList需要的结构:
// 按category分组为键值对结构 const groupedObj = products.reduce((acc, product) => { const cate = product.category; acc[cate] = acc[cate] || []; acc[cate].push(product); return acc; }, {}); // 转换为SectionList要求的[{title, data}, ...]结构 const sectionData = Object.entries(groupedObj).map(([title, data]) => ({ title, data }));
从你已有的中间结构转换
如果已经得到了类似这样的中间结构:
[ { "category1": [{"product1"}, {"product2"}], "category2": [{"product3"}, {"product4"}] } ]
只需取出对象后用Object.entries转换即可:
const intermediateData = [ { category1: [...], category2: [...] } ]; const sectionData = Object.entries(intermediateData[0]).map(([title, data]) => ({ title, data }));
直接用于SectionList
转换后的sectionData可以直接传给SectionList的sections属性:
import { SectionList, Text } from 'react-native'; // ... <SectionList sections={sectionData} renderItem={({ item }) => <Text>{item.name}</Text>} // 渲染每个产品 renderSectionHeader={({ section }) => <Text style={{ fontWeight: 'bold' }}>{section.title}</Text>} // 渲染分类标题 />
内容的提问来源于stack exchange,提问作者Lorenzo Boga
相关产品推荐
相关产品推荐

