我有一个使用钩子实现的相当基本的FlatList组件。该列表仅从随机用户API加载数据,并通过无限滚动延迟加载其他数据。我遇到的唯一视觉问题是,当我将新数据与当前数据合并时,附加的新数据在完全渲染之前会非常短暂地闪烁。不知道是什么原因造成的。
const useRestApi = (url) => {
const [ data, setPeople ] = useState([]);
const [ page, setPage ] = useState(1);
const [ results, setResults ] = useState(20);
const [ loading, setLoading ] = useState(false);
useEffect(() => {
const fetchPeople = async () => {
setLoading(true);
const response = await fetch(`${url}&page=${page}&results=${results}`);
const json = await response.json();
if(page !== 1)
setPeople([...data, ...json.results]);
else
setPeople(json.results);
setLoading(false);
}
fetchPeople();
}, [page]);
return [{data, loading, page}, setPage, setResults];
}
const App: () => React$Node = () => {
const [{ data: people, loading, page }, setPage, setResults] = useRestApi(`https://randomuser.me/api?&seed=ieee`);
return (
<>
<StatusBar barStyle="dark-content" />
<SafeAreaView>
<FlatList
data={people}
onEndReachedThreshold={0.2}
keyExtractor={(item, index) => index.toString()}
renderItem={({item, index}) => (
<View key={index} style={styles.listItem}>
<Text style={styles.listItemHeader}>{item.name.first} {item.name.last}</Text>
<Text style={styles.listItemSubHeader}>{item.location.country}</Text>
<Text style={styles.listItemBody}>{item.location.street.number} {item.location.street.name}</Text>
<Text style={styles.listItemBody}>{item.location.city} {item.location.state} {item.location.postcode}</Text>
</View>
)}
refreshing={loading}
onRefresh={() => {setResults(20); setPage(1);}}
onEndReached={() => {setResults(5); setPage(page + 1);}}
ItemSeparatorComponent={() => ItemSeparatorComponent}
ListFooterComponent={() => loading ? ListFooterComponent : null}
/>
</SafeAreaView>
</>
);
};