How to stop react re-rendering component, if part of the state changes?

对着背影说爱祢 提交于 2020-04-18 05:44:26

问题


Is there a way to stop react re-rendering if only part of state changes?

The problem is that every time I hover on a marker a popup is opened or closed and it causes all the markers to re-render even though mystate is not changing only activePlace state is changing. console.log(myState); is running every time I hover in and out of the marker.

I tried to use useMemo hook but couldn't figure out how to use it. Any help?

Here is my code:

import React, { useEffect, useState } from 'react';
import { Map, TileLayer, Marker, Popup } from 'react-leaflet';
import axios from 'axios';
import { v4 as uuidv4 } from 'uuid';
import { Icon } from 'leaflet';

const myicon = new Icon({
  iconUrl: './icon.svg',
  iconSize: [20, 20]
});

const MyMap = () => {
  const [myState, setMyState] = useState(null);
  const [activePlace, setActivePlace] = useState(null);

  const getData = async () => {
    let response = await axios
      .get('https://corona.lmao.ninja/v2/jhucsse')
      .catch(err => console.log(err));

    let data = response.data;
    setMyState(data);

    // console.log(data);
  };

  useEffect(() => {
    getData();
  }, []);

  if (myState) {
    console.log(myState);
    return (
        <Map
          style={{ height: '100vh', width: '100vw' }}
          center={[14.561, 17.102]}
          zoom={1}
        >
          <TileLayer
            attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors &copy; <a href="https://carto.com/attributions">CARTO</a>'
            url={
              'https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png'
            }
          />

          {myState.map(country => {
            return (
              <Marker
                key={uuidv4()}
                position={[
                  country.coordinates.latitude,
                  country.coordinates.longitude
                ]}
                onmouseover={() => {
                  setActivePlace(country);
                }}
                onmouseout={() => {
                  setActivePlace(null);
                }}
                icon={myicon}
              />
            );
          })}

          {activePlace && (
            <Popup
              position={[
                activePlace.coordinates.latitude,
                activePlace.coordinates.longitude
              ]}
            >
              <div>
                <h4>Country: {activePlace.country}</h4>
              </div>
            </Popup>
          )}
        </Map>
    );
  } else {
    return <div>Loading</div>;
  }
};

export default MyMap;


回答1:


This line is your problem:

key={uuidv4()}

Why are you creating a unique ID on every render? The point of an ID is that it stays the same between renders so that React knows that it doesn't have to re-draw that component in the DOM.

There are two stages that happen whenever state changes, the render phase and the commit phase.

The render phase happens first, and this is where all of your components execute their render functions (which is the entire component in the case of a function component). The JSX that is returned is turned into DOM nodes and added to the virtual DOM. This is very efficient and is NOT the same as re-rendering the actual DOM.

In the commit phase, the new virtual DOM is compared to the real DOM, and any differences found in the real DOM will be re-rendered.

The point of React is to limit the re-renders of the real DOM. It is not to limit the recalculation of the virtual DOM.

This means that it is totally fine fine for this entire component to run its render cycle when activePlace changes.

However, because you're giving a brand new ID to each country on every render cycle, the virtual DOM thinks that every country has changed (it uses IDs to compare previous DOM values), so all the countries in the actual DOM also get re-rendered, which is probably why you're seeing issues with lag.

The ID should be something related to the country, e.g. a country code, not just a random UUID. If you do use random UUIDs, save them with the country so that the same one is always used.



来源:https://stackoverflow.com/questions/60909344/how-to-stop-react-re-rendering-component-if-part-of-the-state-changes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!