Jahir CU
Jahir CU

Reputation: 121

The whole map rendering every time when state got changed

I am using react native maps in my project. I want to draw polygons based on the search without load the whole map again. The whole map is re-render instead of drawing the polygon itself.

I have the logic like these.

_getMapData will render the below map and polygon based on the search. It will call on every filter change or componentWillMount.

<MapView  initialRegion={region} zoomEnrabled>
              {mapData.map((data, index) => (
                <MapView.Polygon
                  key={index}
                  coordinates={data.coordinates}
                  fillColor={data.properties.polygonColor}
                  strokeColor="rgba(88, 136, 177, 0)"
                  strokeWidth={0}
                  tappable
                />
              ))}
</MapView>

the search filter screen is different and when the search is filled just navigating to the map screen. Map screen has the _getMapData function.

Upvotes: 1

Views: 1953

Answers (2)

blaz
blaz

Reputation: 4068

Based on last comment from OP that the data is stored in redux, there is one possible solution: excluding any data related to polygon from component holding <Map> to avoid re-render. Polygons should be rendered inside another component, using Fragment provided in React v16+.

class MapPolygons extends React.Component {
   ...
   render() {
       return (
          <>
              {mapData.map((data, index) => (
                <MapView.Polygon
                  key={index}
                  coordinates={data.coordinates}
                  fillColor={data.properties.polygonColor}
                  strokeColor="rgba(88, 136, 177, 0)"
                  strokeWidth={0}
                  tappable
                />
              ))}
          </>
       )
   }
}

and in your original component:

<MapView  initialRegion={region} zoomEnrabled>
  <MapPolygons />
</MapView>

Again, mapData or any trace of data which can update polygon should be removed from component containing <MapView>, or if it's not possible, they should be handle in shouldComponentUpdate to avoid unwanted re-render.

Upvotes: 0

whd.nsr
whd.nsr

Reputation: 693

Of course the component will re-render after every change on the state, this is how it works on react/react-native and could be a common issue sometimes.

However, you can use shouldcomponentupdate to prevent that the whole component re-render again once the state changes.

Upvotes: 0

Related Questions