我测试了 FlatList。这是我想做的:
1.使用componentDidmount获取10条初始数据
2. 向下滚动可获取另外 10 条数据
App.js
import React from 'react';
import {
View,
SafeAreaView,
Text,
FlatList,
} from 'react-native';
import throttle from 'lodash.throttle';
import { tmpPosts } from './src/data/tmpdata';
class App extends React.Component {
constructor(props) {
super(props);
this.page = 0;
this.state = {
posts: [],
};
this.getMoreDataThrottled = throttle(this.getMoreData, 3000);
}
componentDidMount() {
console.log('comoponentDidMount')
this.getMoreDataThrottled();
}
componentWillUnmount() {
this.getMoreDataThrottled.cancel();
}
getMoreData = () => {
console.log('start getMoreData')
const tmpList = []
for (let i = 0; i < 10; i++ ) {
tmpList.push(tmpPosts[this.page])
this.page += 1;
}
this.setState(prevState => ({
posts: prevState.posts.concat(tmpList)
}));
}
renderPost = ({item}) => {
console.log(item.id)
return (
<View style={{height: 200}}>
<Text>{item.id}</Text>
</View>
);
};
render() {
return (
<SafeAreaView>
<FlatList
data={this.state.posts}
renderItem={this.renderPost}
keyExtractor={post => String(post.id)}
initialNumToRender={10}
onEndReachedThreshold={0.01}
onEndReached={this.getMoreDataThrottled}
/>
</SafeAreaView>
);
}
}
export default App;
tmpdata.js
let num = 0;
export const tmpPosts = [
{id: String(num += 1)},
{id: String(num += 1)},
.
.
.
]
我实现了我想要的,但是渲染发生了很多。
这是console.log
comoponentDidMount
start getMoreData
1
2
3
.
.
.
8
9
10
1
2
3
.
.
.
8
9
10
start getMoreData
1
2
3
.
.
.
8
9
10
1
2
3
.
.
.
18
19
20
start getMoreData
1
2
3
.
.
.
18
19
20
1
2
3
.
.
.
28
29
30
看来日志的意思是:
1、每次都会重新渲染两次。
2. FlatList渲染num增加,因为它也渲染旧数据。
我检查了类似的问题,这似乎是 FlatList 的正常行为。
FlatList renderItem 被调用多次 https://stackoverflow.com/questions/51365912/flatlist-renderitem-is-called-multiple-times
FlatList 调用两次 https://stackoverflow.com/questions/48357524/flatlist-calling-twice
https://github.com/facebook/react-native/issues/14528 https://github.com/facebook/react-native/issues/14528
不过我担心当数据达到100以上时应用程序会变慢并崩溃。
FlatList 性能的最佳解决方案是什么?
shouldComponentUpdate 防止不必要的重新渲染,例如已经渲染的旧数据?