【问题标题】:Adding an item to ScrollView without re-rendering all items在不重新渲染所有项目的情况下将项目添加到 ScrollView
【发布时间】:2017-11-16 16:45:44
【问题描述】:

在我当前的用例中,我将项目添加到 ScrollView。我注意到,如果我将一个项目添加到位于 state 中的项目集合中,所有项目都会重新呈现。

我有什么解决方法吗? 当前的实现必须是ScrollView,因此更改为FlatList 或List 的任何其他实现都无关紧要。

<View style={{flex: 1}}>
    <ScrollView>
      <TouchableWithoutFeedback accessible={false}>
        <View style={{flexDirection: 'column', alignItems: 'center'}}>
        {this.state.items.map(( item, key ) =>
        (
          <Flag country={item} key={key} />
        ))}
        </View>
      </TouchableWithoutFeedback>
    </ScrollView>
  </View>

谢谢

【问题讨论】:

    标签: react-native react-native-scrollview


    【解决方案1】:

    如果您的项目是 PureComponent,当您将新项目添加到列表时,它们将不会再次呈现,除非它们的道具已更改...或者您可以实现 shouldComponentUpdate 常规组件中的方法,并指定该组件应何时再次渲染。

    代码:

    滚动视图:

    <ScrollView>
        {data.map(item =>
            <ScrollViewItem itemInfo={item} />
        )}
    </ScrollView>
    

    带有 PureComponent 的 ScrollViewItem:

    class ScrollViewItem extends React.PureComponent {
        ...
        render() {
            ...
        }
    }
    

    带有 shouldComponentUpdate 的 ScrollViewItem:

    class ScrollViewItem extends React.Component {
    
        shouldComponentUpdate({ itemInfo }) {
            if(itemInfo.id != this.props.itemInfo) {
                return true;//this component will update
            }
    
            return false;//this component won't update 
        }
        ...
        render() {
            ...
        }
    }
    

    【讨论】:

      【解决方案2】:

      我会检查使用 FlatList 而不是使用来自一组状态的地图来呈现 ScrollView。从本质上讲,一旦您更新 this.state.items,您就要求重新渲染与该状态相关的任何内容。

      我已经使用了这个资源,它应该可以帮助你升级你的代码:

      http://matthewsessions.com/2017/05/15/optimizing-list-render-performance.html

      【讨论】:

      • 我知道 FlatList,但正如我提到的,它必须是 ScrollView,有什么方法可以添加项目而不重新渲染 ScrollView 中的所有项目?
      • 对不起。我实际上的意思是使用 FlatList 的“概念”而不是使用 FlatList ?。换句话说,考虑创建可回收的子视图。
      【解决方案3】:

      在我的例子中,将flexShrik: 0 设置为滚动视图内的所有元素,解决了这个问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-29
        • 2021-12-10
        • 2021-10-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多