我有一个
ListHeaderComponent
,里面有一个水平的 FlatList
,但没有正确渲染。 (它只会在我热重载时呈现)。
这是我的代码
const getData = async () => {
Promise.all([getVenues(), getCategories()])
.then(() => {
setLoading(false);
})
.catch((error) => {
setLoading(false);
console.log(error);
});
};
const listHeaderComponent = useCallback(() => {
return <HomeListHeader language={language} categories={categories} />;
}, [language]);
return (
<>
<Stack.Screen
options={{
header: () => <HomeHeader headerPress={handleHeaderPress} />,
}}
/>
{loading ? (
<View />
) : (
<FlatList
data={venues}
ListHeaderComponent={listHeaderComponent}
renderItem={(item) => {
return renderItem(item);
}}
keyExtractor={(item) => item.id}
style={[styles.container, { backgroundColor: backgroundColor }]}
/>
)}
</>
);
export default function HomeListHeader({ language, categories }) {
const colorScheme = useColorScheme();
const backgroundColor = Colors[colorScheme ?? "light"].background;
const lightGray = Colors[colorScheme ?? "light"].lightGray;
const tintColor = Colors[colorScheme ?? "light"].tint;
const router = useRouter();
const handleCategoryPress = (item) => {
router.push({
pathname: "home/category",
params: {
categoryName: item[language].name,
},
});
};
const renderItem = useCallback(({ item }) => {
return (
<Pressable
onPress={() => handleCategoryPress(item)}
style={[styles.itemContainer, { backgroundColor: lightGray }]}>
<Text style={[styles.itemName, { color: tintColor }]}>
{item[language].name}
</Text>
</Pressable>
);
});
const itemSeparatorComponent = () => {
return <View style={{ width: 10 }} />;
};
return (
<FlatList
data={categories}
renderItem={renderItem}
ItemSeparatorComponent={itemSeparatorComponent}
horizontal
contentInset={{ right: 40 }}
showsHorizontalScrollIndicator={false}
showsVerticalScrollIndicator={false}
style={[styles.container, { backgroundColor: backgroundColor }]}
/>
);
}
我似乎无法弄清楚这是为什么。我做错了什么?
读取 FlatList、Props ListHeaderComponent 和动态平面列表数据
我在 ListHeaderComponent 的依赖项中添加了类别,这解决了问题
const listHeaderComponent = useCallback(() => {
return <HomeListHeader language={language} categories={categories} />;
}, [language, categories]);