【问题标题】:Performant way to display multiple components in React native在 React Native 中显示多个组件的高效方式
【发布时间】:2017-03-02 18:26:58
【问题描述】:

多次渲染组件时,我在 React Native 中遇到了非常缓慢的性能。我有一组对象,其中包含组件要使用的信息。目前该数组有大约 17 个对象,因此同一个组件将在 ScrollView 中显示 17 次。从<PreviousComponent /> 切换到<Container /> 时,JS 帧速率下降到 -2 fps。我只是展示与问题相关的代码块,用于解释目的。另请注意,我使用的导航是来自 react-community 的 react-navigation。 <EachCard /> 是另一个包含一些 Text 和 View 组件的组件。我想我使用的方法是标准的。

我阅读了性能页面https://facebook.github.io/react-native/docs/performance.html。我没有console.log,也将开发模式设置为false。

那么为什么 JS fps 会下降到 -2,为什么加载 17 个组件需要几秒钟?我使用的是真实设备(LG G4 @6.0)

class PreviousComponent extends React.Component {
render(){
    return(
        <Button onPress={()=> this.props.navigate('Container', {info: listings})} title="Go to Container" />
    );
  }
}

class Container extends React.Component {
render(){
    const { params }= this.props.navigation.state;
    let results = params.info.map((each) =>
        <EachCard name={each.name} position={each.position} etc1={each.etc1}  etc2={each.etc2}/>
    );
    return (
        <View>
            <ScrollView>
              {results}
            <ScrollView>
        </View>
    );
  }
}

【问题讨论】:

  • 尝试用列表视图而不是滚动视图重写。它对性能进行了更多优化。
  • 这些组件中是否有任何动画、繁重的图形或异步 api 调用?还是它们只包含一些静态的东西?可以在这里分享 组件的代码吗?

标签: reactjs react-native react-navigation


【解决方案1】:
  1. 在 Scrollview 上使用 Flatlist,将 initialNumToRender={number} 属性添加到 Flatlist,因为它只会显示那些在屏幕上可见的组件并分离其他组件。

  2. 在 Flatlist 的 renderItem 中使用 PureComponent(在你的情况下,它将是每个卡片),这样它们只会在它们的道具发生变化时呈现。

  3. 检查您的组件是否一次又一次地重新渲染(在 render() 或 ComponentWillRecieveProps 中测试放置控制台)如果发生这种情况,请使用 ShouldComponentUpdate。

我认为实施这三点将解决您的问题。

【讨论】:

    【解决方案2】:

    建议对任何类型的列表组件使用 FlatList 或 ListView。它们针对性能进行了优化,并具有内置的内存使用优化

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-08
      • 1970-01-01
      • 2019-01-11
      • 2019-07-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多