简体   繁体   中英

Prevent re-render on state update for only one part of component

I'm using dynamic moving markers in my React-Native application, in order to make the markers move I've got state updates on an interval that re-renders the screen with the new marker positions. I'm also trying to use react-native-maps-directions which uses the google Routes API (which costs money) and I can't allow the routes API to get called twice every second because that seems wasteful (also because I'm poor).

Basically, do you know of a way to keep re-rendering the part that updates marker locations while not re-rendering the routes

Here's my render:

render() {
    return (
      <View>
          <MapView
            allOfMyProps={blahblahProps}
          >

            //This currently does and should re-render every time because I need them to move
            {this.state.markers[1] !== null &&
              this.state.markers.map((marker, index) => (
                <MapView.Marker
                  key={index}
                  coordinate={{
                    latitude: marker.coordinate.latitude,
                    longitude: marker.coordinate.longitude,
                  }}
                />
              ))}

            /// This is what renders the route, I want this to not re-render every time state changes
          <MapViewDirections
              origin={origin}
              destination={destination}
              apikey={GOOGLE_MAPS_API_KEY} //configure this right
              strokeWidth={10}
              strokeColor="green"
           />


          </MapView>
    </View>

I solved it by creating a new external class-based component and using another shouldComponentUpdate which tests to see if the destination prop updated. If it updated, then re-render the component, if not it'll send back what it already rendered. HUGE thanks to Drew Reese for the hint!

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