Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

react native - FlatList ScrollView Error on any State Change - Invariant Violation: Changing onViewableItemsChanged on the fly is not supported

onViewableItemsChanged does not seem to work when there is a state change in the app. Is this correct?

Seems like it wouldn't be very useful if this were the case....

Otherwise, users will be forced to us onScroll in order to determine position or something similar...

Steps to Reproduce

  1. Please refer to snack
  2. Repo has also been uploaded at github
  3. Any state change produces an error when using onViewableItemsChanged
  4. What does this error even mean?

Note: Placing the onViewableItemsChanged function in a const outside the render method also does not assist...

<FlatList
    data={this.state.cardData}
    horizontal={true}
    pagingEnabled={true}
    showsHorizontalScrollIndicator={false}
    onViewableItemsChanged={(info) =>console.log(info)}
    viewabilityConfig={{viewAreaCoveragePercentThreshold: 50}}
    renderItem={({item}) =>
        <View style={{width: width, borderColor: 'white', borderWidth: 20,}}>
            <Text>Dogs and Cats</Text>
        </View>
    }
/>

Actual Behavior

Error

image

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Based on @woodpav comment. Using functional components and Hooks. Assign both viewabilityConfig and onViewableItemsChanged to refs and use those. Something like below:

  const onViewRef = React.useRef((viewableItems)=> {
      console.log(viewableItems)
      // Use viewable items in state or as intended
  })
  const viewConfigRef = React.useRef({ viewAreaCoveragePercentThreshold: 50 })


<FlatList
      horizontal={true}
      onViewableItemsChanged={onViewRef.current}
      data={Object.keys(cards)}
      keyExtractor={(_, index) => index.toString()}
      viewabilityConfig={viewConfigRef.current}
      renderItem={({ item, index }) => { ... }}
/>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...