简体   繁体   中英

React Native - How to compare two Animated.Values in shouldComponentUpdate?

I am optimizing my flatlist items (progressive images) and to avoid extending React.PureComponent I have decided to implement my own shouldComponentUpdate life-cycle method.

My progressive images have two animated values:

 1. thumbnailOpacity 2. imageOpacity

And my should component update must look something like this:

state = {
   isLoading: true,
   thumbnailOpacity: new Animated.Value(0),
   imageOpacity: new Animated.Value(0)
}

shouldComponentUpdate(nextProps, nextState) {
  /*
    React's PureComponent implement a shouldComponentUpdate with shallow comparison.
    This is expensive here, because it need to check all our props. For a good bit-level performance,
    use the strictest rules for our list item.

    This component must re-render only when the state change.
  */

  return (
     nextState.isLoading !== this.state.isLoading ||
     nextState.thumbnailOpacity !== this.state.thumbnailOpacity ||
     nextState.imageOpacity !== this.state.imageOpacity
  );        
}

But as Animated values are not primitive data types, I don't know how to do that without a shallow comparison.

Any ideas? Thank you.

From your state initialisation:

state = {
   ...
   thumbnailOpacity: new Animated.Value(0),
   imageOpacity: new Animated.Value(0)
}

You should be able to access it like this:

this.state.thumbnailOpacity._value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM