I have been using map function to render data with Flatlist in my React Native application. But the same data is being rendered thrice for some reason. Here's what I have right now:
renderItem = ({ item, index }) => { if (item === null) return <View key="post_" />; const imageURI = this.props.categories; const mainCategories = imageURI.filter( category => category.parent === 0 ); return mainCategories.map((data) => { return ( <TouchableOpacity activeOpacity={0.9} style={[styles.panelTwo]} onPress={() => this.onRowClickHandle(item)} > <ImageCache uri={data.image === null? Images.defaultPayment: data.image.src} key={data.id} style={styles.imagePanelTwo} /> <Text numberOfLines={1} style={styles.nameTwo}> {data.name} </Text> </TouchableOpacity> ); }) }; render() { const {categories,showSorting} = this.props; const mainCategories = this.props.categories.filter( category => category.parent === 0 ); return ( <View> <View style={[styles.flatWrap]}> <FlatList contentContainerStyle={styles.flatlist} data={mainCategories} keyExtractor={item => `post__${item.id}`} renderItem={this.renderItem} showsHorizontalScrollIndicator={false} horizontal /> </View> </View> ); } }
I can't figure out why the same data is rendering thrice in this situation. Also the mainCategories is like this:
except that it's showing three times.
Let's say your data array is [1, 2, 3]
. In this case, FlatList will loop over it and renders them one by one and will look like:
<Text>1</Text>
<Text>2</Text>
<Text>3</Text>
But in renderItem
you do the loop again and say, render the whole array for every row and your result is:
<Text>1</Text>
<Text>2</Text>
<Text>3</Text>
<Text>1</Text>
<Text>2</Text>
<Text>3</Text>
<Text>1</Text>
<Text>2</Text>
<Text>3</Text>
Change
renderItem = ({ item, index }) => {
if (item === null) return <View key="post_" />;
const imageURI = this.props.categories;
const mainCategories = imageURI.filter(
category => category.parent === 0
);
return mainCategories.map((data) => {
return (
<TouchableOpacity
activeOpacity={0.9}
style={[styles.panelTwo]}
onPress={() => this.onRowClickHandle(item)}
>
<ImageCache uri={data.image === null ? Images.defaultPayment : data.image.src} key={data.id} style={styles.imagePanelTwo} />
<Text numberOfLines={1} style={styles.nameTwo}>
{data.name}
</Text>
</TouchableOpacity>
);
})
};
To
renderItem = ({ item }) => {
if (item === null) return <View key="post_" />;
const onPressItem = () => this.onRowClickHandle(item)
return (
<TouchableOpacity
activeOpacity={0.9}
style={styles.panelTwo}
onPress={onPressItem}
>
<ImageCache uri={data.image?.src || Images.defaultPayment} key={data.id} style={styles.imagePanelTwo} />
<Text numberOfLines={1} style={styles.nameTwo}>{data.name}</Text>
</TouchableOpacity>
);
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.