React Native FlatList returned from a function or const rerenders from the top when an item is interacted with

百般思念 提交于 2020-06-28 04:15:11

问题


I'm trying to put a flatlist checklist into a react native tab view, to do that you need to declare the flatlist as a const so it can be used like . Unfortunately whenever I click on an item at the bottom of the list it pops back to the top and rerenders the list. This problem doesn't occur when a flatlist is rendered directly into your components render function.

I've made a simplified version of what I mean. https://snack.expo.io/ecO7YYlVZ Is the version where clicking an item pops to the top https://snack.expo.io/1iQ!ILk4B Is the version where clicking an item doesn't pop to the top.

The only difference between the two is the not working version is like this

    const Dat = () => {
  return (
    <FlatList
      style={styles.container}
      data={rowsData}
      renderItem={this.renderItem}
      keyExtractor={extractKey}
    />
  );
};
return <Dat />;

Whereas the working version is like this

    return (
  <FlatList
    style={styles.container}
    data={rowsData}
    renderItem={this.renderItem}
    keyExtractor={extractKey}
  />
);

EDIT: I need to have the flatlist in a way that I can add it to a tab using react-native-tab-view: https://github.com/react-native-community/react-native-tab-view


回答1:


Dat component must be outside of render() because it reinitializes the whole component and then rerenders that which cause that behavior

instead, when you create a component outside of the render(), the component itself does not reinitialize only data updated

Your Dat component

const Dat = () => {
  return (
    <FlatList
      style={styles.container}
      data={rowsData}
      renderItem={this.renderItem}
      keyExtractor={extractKey}
    />
  );
};

Check the example with the outside of render()

https://snack.expo.io/@jsfit/flatlist



来源:https://stackoverflow.com/questions/62261038/react-native-flatlist-returned-from-a-function-or-const-rerenders-from-the-top-w

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!