首页 > 解决方案 > React Native FlatList - 多次重新渲染/安装子项目

问题描述

https://snack.expo.io/SykFiqQ8E

我一直在编写一个使用 FlatList ( https://facebook.github.io/react-native/docs/flatlist ) 的 react-native 应用程序。我注意到列表中的子项存在一些性能问题,如果我向数据集添加更多数据,FlatList 组件将多次重新渲染/安装子项。该事实对用户不可见,但在堆栈跟踪中,我能够证明它多次渲染该子项,只需在每次渲染时执行警报即可。

查看问题的现场演示,然后单击添加项目。它会在每个项目中多次提醒子项目。我不知道我的实现是否错误,或者我是否需要在 react native 的 github 上创建问题。

import * as React from 'react';
import { Text, View, StyleSheet, FlatList, Alert, Button } from 'react-native';
import { Constants } from 'expo';

export default class App extends React.Component {
  state = {
    data: [{key: 'i love rn but why do my items render/mount more than once'}]
  }

  addItem() {
    const data = this.state.data.concat({key: "item#" + this.state.data.length.toString()})
    this.setState({ data })
  }

  render() {
    return (
      <View style={styles.container}>
        <FlatList
          data={this.state.data}
          renderItem={({item}) => <Text>{item.key} {Alert.alert(item.key)}</Text>}
        />
        <Button onPress={this.addItem.bind(this)} title="Add Item" />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  }
});

我不确定他们的反应速度有多快,所以希望在这里获得一些反馈。

标签: javascriptreact-native

解决方案


推荐阅读