React Native Listing

In this article, I will not tell you that you need to use as little content as possible to display or cache images. No! We will only talk about real list optimization and it doesn’t matter what we need to display, because if the client says I want and you can’t argue with him.


Let's start with the simplest example. Let's say we have an array.


const list = [{ _id: 567456, label: “CodingChipmunks” }, ...]  

What is the easiest way to render a small list? It is correct to use a method .mapthat returns a new array and we can display the entire list. Well, let's look at one example:


render() {  
    return (
        <View>
            {list.map((item) => (  
                <View>  
                    <Text>{item.label}</Text>  
                <View>))}

        </View>
    )  
}  

Correctly? No! Never do that!


  • First, you always need to specify key for each item. And please do not use for this index element in the array. Below I will tell you why.
  • Secondly, the code looks messy
  • Third, do not use anonymous functions

Why not do it like this:


renderItem = (item) => (
    <View key={item._id}>  
        <Text>{item.label}</Text>  
    <View>
)

render() {  
    return (
    <View>
        {list.map((item) => this.renderItem(item)}
    </View>)  
}  

or so:


const Item = (item) => (  
    <View >  
        <Text>{item.label}</Text>  
    <View>  
)

class List extends React.Component {  

render() {  
    return (
        <View>
            {list.map((item) => <Item key={item._id} />}
        </View>)  
    }  
}

Is it much better now? Not really.


. .map. render item . . . - . ? ,


.
“? ? ? ?” .

:


    render() {  
        return (
            <View>
                {list.map(this.renderItem)}
            </View>
        )  
    }

PureComponent item.


!


class Item extends React.PureComponent {
...
}

!


?


. . ? FlatList. Flatlist ? . .
:


const list = [loyaltyCard1, loyaltyCard2, … , loyaltyCard100];
renderItem = ({ item: loyaltyCard, index }) => (...)

keyExtractor = loyaltyCard => loyaltyCard._id  

render() {  
    <FlatList
        keyExtractor={this.keyExtractor} 
        data={list}
        renderItem={this.renderItem} />  
}

key, keyExtractor, .
renderItem :


  1. item —
  2. index —
  3. separator —

?


, extraData. .


getItemLayout.


ReactNative


getItemLayout={(data, index) => (
{length: ITEM_HEIGHT, offset: ITEM_HEIGHT * index, index}
)}  

? getLayout


onLayout = (event) => {  
    const {x, y, width, height} = event.nativeEvent.layout;  
    do something with layout
}
renderItem = ({ item: loyaltyCard, index}) => (
    <View onLayout={this.onLayout} />
)

? initialNumToRender maxToRenderPerBatch. .


initialNumToRender .
maxToRenderPerBatch


  • lazyLoad onEndReached onEndReachedThreshold .


.


?
removeClippedSubviews — true .


  • .

getItemLayout.


. ReactNative


All Articles