首页 > 解决方案 > 反应原生。VirtualizedList:PureComponent、shouldComponentUpdate等

问题描述

我从 API 得到一个大数组,我想显示这个数组中的图像。我做到了,但它不能正常工作。

React native 仅显示 8 张图像并向我发送下一个信息(VirtualizedList:您有一个更新缓慢的大型列表 - 确保您的 renderItem 函数呈现遵循 React 性能最佳实践的组件,如 PureComponent、shouldComponentUpdate 等)

除了 React Native 的推荐,我如何显示所有图像?

任何人都可以帮助我吗?提前致谢!

我的代码:

import React, { useEffect, useState } from 'react';
import { ActivityIndicator, FlatList, View, Image, SafeAreaView, StyleSheet } from 'react-native';

export default SignInScreen = () => {
  const [isLoading, setLoading] = useState(true);
  const [data, setData] = useState([]);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/photos')
      .then((response) => response.json())
      .then((json) => setData(json))
      .catch((error) => console.error(error))
      .finally(() => setLoading(false));
  });

  return (
    <SafeAreaView>
      {isLoading ? <ActivityIndicator/> : (
        <View style={styles.container}>
          <FlatList
            data={data}
            keyExtractor={({ id }, index) => id.toString()}
            renderItem={({ item }) => <Image style={styles.imageView} source={{ uri: item.thumbnailUrl }} />}
          />
        </View>
      )}
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    paddingVertical: 60,
    paddingHorizontal: 20,
  },
  imageView: {
    width: 150,
    height: 150 ,
    margin: 7,
    borderRadius : 7
  }
})

标签: reactjsreact-native

解决方案


使用 PureComponent 在 FlatList 中创建一个组件,这样当图像数组没有变化时,FlatList 就不会重新渲染。


推荐阅读