使用useEffect挂钩时出现FlatList性能警告问题

 收藏

使用useEffect挂钩获取数据时,我在FlatList中收到警告。

这是重现此问题的完整组件:

import React, { useState, useEffect } from "react";
import {
  Text,
  View,
  FlatList,
  ActivityIndicator,
  SafeAreaView,
  Button
} from "react-native";

const Test = props => {
  const [people, setPeople] = useState([]);
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(1);

  useEffect(() => {
    setLoading(true);
    fetch(`http://jsonplaceholder.typicode.com/photos?_start=${page}&_limit=20`)
      .then(res => res.json())
      .then(res => {
        //console.log(res);
        setPeople(people => [...people, ...res]);
        setLoading(false);
      });
  }, [page]);

  const loadMore = () => {
    setPage(page + 20);
  };

  return (
    <SafeAreaView style={{ flex: 1 }}>
      <FlatList
        data={people}
        keyExtractor={item => item.id}
        renderItem={({ item }) => (
          <View>
            <Text>{item.id}</Text>
            <Text>{item.title}</Text>
          </View>
        )}
        ListFooterComponent={
          loading ? (
            <ActivityIndicator />
          ) : (
            <Button title="Load More" onPress={loadMore} />
          )
        }
      />
    </SafeAreaView>
  );
};

export default Test;

这是我得到的警告

VirtualizedList:您有一个更新缓慢的大列表-确保您的renderItem函数呈现遵循React性能最佳实践的组件,例如PureComponent,shouldComponentUpdate等。Object {     “ contentLength”:4418,     “ dt”:705,     “ prevDt”:669,   }

It basically tells me to use PureComponent or shouldComponentUpdate, though, but AFAIK both do not work with either a functional component or the useEffect hook, do they?

尽管我没有注意到(巨大的)性能下降,但是我仍然想知道是否存在解决此问题的解决方法。任何帮助,将不胜感激。非常感谢你。

编辑:使用PureComponent不能解决问题:

创建了PureComponentTest.js

import React from "react";
import { Text, View, StyleSheet, TouchableOpacity } from "react-native";

const PureComponentTest = props => {
  return (
    <View>
      <Text>{props.id}</Text>
      <Text>{props.title}</Text>
    </View>
  );
};

export default PureComponentTest;

And in my Component I updated renderItem={renderItems}:

  const renderItems = itemData => {
    return (
      <PureComponentTest
        id={itemData.item.id}
        title={itemData.item.title}
      />
    );
  };
回复
  • Oo傻吖頭 回复

    我真的没有发现您的组件有任何问题。这是一个非常简单的纯组件。可能只是因为获取的数据太大。尝试减少每次获取的页面数。说5或10页