关于reactjs:React Native。 VirtualizedList:PureComponent,shouldComponentUpdate等

React Native. VirtualizedList: PureComponent, shouldComponentUpdate, etc

我从API获得了一个大数组,我想显示该数组中的图像。 我做到了,但无法正常工作。

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

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

有人可以帮我吗? 提前致谢!

我的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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
  }
})

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