<FlatList
data={[{key: 'a'}, {key: 'b'}]}
renderItem={({item}) => <Text>{item.key}</Text>}
/>
演示如何利用PureComponent來進一步優化性能和減少bug產生的可能(這段需要了解shouldComponentUpdate的機制,以及Component和PureComponent的不同)
class MyListItem extends React.PureComponent {
_onPress = () => {
this.props.onPressItem(this.props.id);
};
render() {
return (
<SomeOtherWidget
{...this.props}
onPress={this._onPress}
/>
)
}
}
class MyList extends React.PureComponent {
state = {selected: (new Map(): Map<string, boolean>)};
_keyExtractor = (item, index) => item.id;
_onPressItem = (id: string) => {
// updater functions are preferred for transactional updates
this.setState((state) => {
// copy the map rather than modifying state.
const selected = new Map(state.selected);
selected.set(id, !selected.get(id)); // toggle
return {selected};
});
};
_renderItem = ({item}) => (
<MyListItem
id={item.id}
onPressItem={this._onPressItem}
selected={!!this.state.selected.get(item.id)}
title={item.title}
/>
);
render() {
return (
<FlatList
data={this.props.data}
extraData={this.state}
keyExtractor={this._keyExtractor}
renderItem={this._renderItem}
/>
);
}
}
import React, {Component} from 'react'
import {StyleSheet, View, FlatList, Text} from 'react-native'
var data = [
{"id":1, title:"title-1"},
{"id":2, title:"title-2"},
{"id":3, title:"title-3"},
{"id":4, title:"title-4"},
{"id":5, title:"title-5"},
{"id":6, title:"title-6"},
{"id":7, title:"title-7"}
]
export default class RecordList extends Component {
render() {
return(
<FlatList
data={data}
keyExtractor={(item, index) => item.id}
renderItem={({item, index}) => <Text>{item.title}</Text>}
ItemSeparatorComponent={() => this.separator()}
onEndReachedThreshold = {0.5}
onEndReached={()=> {/*快到底了,要加載更多資料..等*/} }
ListFooterComponent={() => this.footerComponent()}
/>
);
}
separator() {
return <View style={styles.separator} />
}
footerComponent() {
return (
<View style={styles.footerView}>
<Text>最後一筆</Text>
</View>
)
}
}
const styles = StyleSheet.create({
separator: {
height: 1,
backgroundColor: 'red',
},
footerView: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
},
});