![](/img/trans.png)
[英]React Native - VirtualizedList: You have a large list that is slow to update
[英]VirtualizedList: You have a large list that is slow to update How can i fix this problem
我遇到一個錯誤,顯示“VirtualizedList:您有一個更新速度很慢的大列表 - 確保您的 renderItem function 呈現遵循 React 性能最佳實踐的組件,如 PureComponent、shouldComponentUpdate 等。” 誰能幫我解決我代碼中的這個問題? 另外,有時帖子會在 2-3 秒后加載,我怎樣才能加載密集?
主頁:
export default function Home({ navigation }) {
const [userdata, setUserdata] = useState(null);
return (
<View style={styles.container}>
<StatusBar />
<ButtomNavbar navigation={navigation} page={'home'} />
<TopNavbar navigation={navigation} page={'home'} />
<Posts />
</View>
);
}
后期比較:
import { StyleSheet, FlatList } from 'react-native'
import React, { useState, useEffect, useCallback } from 'react';
import PostCard from '../Cards/PostCard';
const Posts = () => {
const [userData, setUserData] = useState([]);
const fetchUserData = useCallback(async () => {
try {
const response = await fetch('http://10.0.2.2:3000/postdata');
const data = await response.json();
setUserData(data);
} catch (err) {
console.error(err);
}
}, []);
useEffect(() => {
fetchUserData();
}, [fetchUserData]);
return (
<FlatList
style={styles.container}
data={userData}
renderItem={({ item, index }) => (
<PostCard
key={index}
username={item.username}
profile_image={item.profile_image}
postImage={item.postImage}
/>
)}
/>
);
}
export default Posts
明信片:
import React from 'react';
import { StyleSheet, Text, View, Image } from 'react-native';
const PostCard = ({ username, profile_image, postImage }) => {
return (
<View style={styles.container}>
<View style={styles.c1}>
<Image source={{ uri: profile_image }} style={styles.profilepic} />
<Text style={styles.username}>{username}</Text>
</View>
<Image source={{ uri: postImage }} style={styles.image} />
</View>
);
};
嘗試將keyExtractor
道具添加到您的FlatList
。 這是一個例子:
return (
<FlatList
style={styles.container}
data={userData}
keyExtractor={(item) => `${item.id}`} <-----add this line
renderItem={({ item, index }) => (
<PostCard
key={index}
username={item.username}
profile_image={item.profile_image}
postImage={item.postImage}
/>
)}
/>
);
"VirtualizedList: You have a large list that is slow to update - make sure your renderItem function renders components that follow React performance best practices like PureComponent, shouldComponentUpdate, etc."
當您嘗試使用 FlatList 呈現過多數據或對象時,此警告基本上會出現,因為當您擁有大量數據時,您必須管理它不會一次又一次地呈現,因為renderItem
在用戶滾動時一次又一次地調用數據消費更多 memory
您可以通過創建 renderItem class 組件並使用PureComponent
而不是React.Component
擴展它來控制此行為
您還可以通過shouldComponentUpdate
方法控制此行為,如本例所示
https://www.geeksforgeeks.org/what-does-shouldcomponentupdate-do-and-why-is-it-important/
如果您認為這會花費您一些時間,那么作為最簡單的解決方案,您可以使用這個庫
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.