Lifecycle methods of components FlatList ScrollToIndex ScrollToEnd etc.

I am using a new FlatList

component
and want to use ScrollToIndex

(or ScrollToEnd

) in lifecycle methods eg componentDidMount

.

I have a let say array of 100 items and I don't want to start rendering at the first item, but at the beginning. Let's say on the 50th subject. When FlatList

only showing one item at a time, it works as desired with some hack as described here: https://github.com/facebook/react-native/issues/13202

componentDidMount() {
  let wait = new Promise((resolve) => setTimeout(resolve, 500));  // Smaller number should work
  wait.then( () => {
    this.refs.flatlist.scrollToIndex({index: 4, animated: true});
  });
}

      

This snippet makes it ScrollToIndex

launched after a few milliseconds of the call componentDidMount

.

But when I use FlatList

where the view contains a 3x3 grid, I just can't get it to work. When I use ScrollToIndex

, and the index is outside the specified props initialNumToRender

, I get an error scrollIndex out of range $ID

that I can't figure out. The presented dataset has everything, for example 100 elements. When I make us out ScrollToEnd

, it stops somewhere in the middle, not at the end. It looks like some kind of error to me, and I don't know any other way how to navigate to the $ X element after initial rendering. Can you help me?

I am grateful for any help or comment.

I tried using React-Native v0.43.0 and v0.44.0 on iOS and Android (emulator and device) and it is always the same.

+3


source to share


2 answers


Are you setting getItemLayout

prop on FlatList?

Check what it says in the React source code for scrollToIndex

- https://github.com/facebook/react-native/blob/master/Libraries/Lists/FlatList.js#L308



This will only really work if your elements are set height. There seems to be no suitable solution for variable height items. I was able to get this to work with a variable height by setting initialNumToRender={indexToScrollTo + 1}

and then using scrollToOffset

instead scrollToIndex

(setting the offset relative to the element you want to scroll). This has obvious performance issues and is really not ideal if you have long lists or your objects have complex rendering.

+4


source


Under these conditions, the VirtualizedList.js warning is raised scrollIndex out of range $ID

:

scrollToIndex(params: {animated?: ?boolean, index: number, viewPosition?: number}) {
    const {data, horizontal, getItemCount} = this.props;
    const {animated, index, viewPosition} = params;
    if (!(index >= 0 && index < getItemCount(data))) {
      console.warn('scrollToIndex out of range ' + index);
      return;
    } ....

      



Maybe make sure your getItemCount is getting the correct count from your data. By default, prop uses data.length, so you might need to specify your own if you haven't already.

+1


source







All Articles