RN解决警告:VirtualizedLists should never be nested inside plain ScrollViews

React Native 开发过程中,如果我们把 FlatList 或者 SectionList 控件放在 ScrollView 中的haul,调试的时候会有如下黄盒警告:

VirtualizedLists should never be nested inside plain ScrollViews with the same orientation
- use another VirtualizedList-backed container instead.

这个警告指明了问题,但是没有给出错在哪,也没给出解决方案。我们一起来看看问题的原因以及解决办法。

为什么将VirtualizedList嵌套在ScrollView中不好?

Virtualized Lists, 是一种带有性能优化的 List,在 List 很大的时候,它会有明显的内存优化结果。怎么个优化法呢?例如一个 List 有一千个 Cell,如果没有优化,这一千个 Cell 都会被渲染并保持在内存中,内存会明显升高。Virtualized lists 的做法是,只让显示在屏幕上的 Cell 渲染,其它的没有显示在屏幕上的 Cell 销毁。这样就节省很多内存。

FlatList 和 SectionList 都是用的 Virtualized Lists。

那现在你把 Virtualized List 放在 ScrollView 中,ScrollView 是要全部渲染的,那么 Virtualized List 就计算不出来哪些 Cell 目前显示在屏幕上,会渲染所有的 Cell,那么它的优势就显现不出来了。这个时候就会抛出上述警告。

怎么解决?

一般情况下,你能把 FlatList 或 SectionList 放在 ScrollView 中, 一定是还有别的控件和 FlatList 并列放在 ScrollView 中的对吧?想让别的控件和 FlatList 一起滚动。

要实现这个一起滚动的效果,你可以把别的控件放在 FlatList 的 ListHeaderComponent 或 ListFooterComponent 中。这样就不需要 ScrollView 了。

例如,之前需要把多个控件放在 ScrollView 中:

render() {
  return (
    <ScrollView>
      <Title>Welcome</Title>
      <Text>Take a look at the list of recipes below:</Text>
      <FlatList
        data={recipes}
        renderItem={renderItem}
      />
      <Footer/>
    </ScrollView>
  );
}

改善后的代码:

render() {
  return (
    <FlatList
      LisHeaderComponent={
      <>
        <Title>Welcome</Title>
        <Text>Take a look at the list of recipes below:</Text>
      </>}
      data={recipes}
      renderItem={renderItem}
      ListFooterComponent={
        <Footer/>
      }/>
  );
}

实现了同样的效果,警告就没了。

本文参考一篇英文博客,觉得有用,就翻译过来。
感谢原作者,原文链接

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值