我希望在一个以类别名称为标题的水平平面列表中显示所有具有相同类别的产品。
是否需要将获取的数据按类别分组,如果需要,如何实现?哪一个更适合这个场景--平面列表还是区段列表。
const HomeScreen = ({ navigation }) => {
const [products, setProducts] = useState<any[]>([]);
const [categories, setCategory] = useState<any[]>([]);
useEffect(() => {
fetch("https://dummyjson.com/products")
.then((response) => response.json())
.then(({ products }) => {
setProducts(products);
})
.catch((error) => console.log(error));
});
return products.length > 0 ? (
<View
style={{
backgroundColor: COLORS.backgroundLight,
marginTop: 20,
}}
>
<View
style={{
width: "100%",
flexDirection: "row",
justifyContent: "space-between",
padding: 16,
}}
>
<TouchableOpacity onPress={() => navigation.openDrawer()}>
<MaterialIcons name="menu" size={30} color="black" />
</TouchableOpacity>
<TouchableOpacity onPress={() => navigation.navigate("CartScreen")}>
<Feather name="shopping-cart" size={30} color="black" />
</TouchableOpacity>
</View>
<FlatList
data={products}
keyExtractor={(products) => products.id.toString()}
numColumns={2}
renderItem={({ item }) => (
<ProductCard
title={item.title}
price={item.price}
image={item.images[0]}
onPress={() => navigation.navigate("ProductDetails", item)}
/>
)}
/>
</View>
) : (
<View
style={{
flex: 1,
justifyContent: "center",
alignItems: "center",
}}
>
<ActivityIndicator size="large" />
</View>
);
};
export default HomeScreen;,我被困在这里面很久了,请帮助
发布于 2022-06-27 05:48:12
我以前也遇到过同样的问题。我用SectionList而不是Flatlist解决了问题。您需要将数据结构更改为类似的内容。
const DATA = [
{
title: "First Category",
data: [...all items of that category]
},
{
title: "Second Category",
data: [...all items of that category]
},
...
]https://stackoverflow.com/questions/72765869
复制相似问题