如何强制一个反应组件不重新渲染?

How to force one react component to not re-render?

我有一个主要的 React 组件(整个页面),其中包含其他几个 UI 项目。其中 UI 项是 OpenLayers 地图。另一个组件是一个文本字段,其中包含当前鼠标指针位置的纬度和经度。

我希望只要鼠标指针在地图上移动,文本字段就会更新。在我的代码的当前状态下,这有效。

问题是每次鼠标移动并且我更新 latitude/longitude 的反应状态值(按预期在文本字段中呈现)时,地图都会重新呈现。这看起来很糟糕,因为每次开始加载地图图块时地图都会闪烁。

所以我有鼠标 latitude/longitude 的位置,但是我无法得到地图而不是 flash/stutter/strobe。

有没有办法从地图组件中获取鼠标事件,并发送到同屏的另一个组件,而不会导致render方法每次都重绘地图?或者 React 是这个项目的错误工具?

请注意,我正在使用 React Redux 来处理一些状态值,例如地图对象。我所有的子组件都是 React 函数式组件,但页面的主要组件是 React class 组件。

如果有帮助,我在地图上设置鼠标侦听器是这样的:

this.props.map.on('pointermove', event => {
  this.setState({
    mouseCoordinates: (event.coordinate),
  });
});

这是我的渲染方法:

render() {
  return (
    <div className="main">
      <p className={noMargPad}>
        {this.state.mouseCoordinates}
      </p>
      <Map
        center={fromLonLat(this.state.center)}
        zoom={this.state.zoom}
      >
        <Layers>
          <TileLayer source={osm()} zIndex={0} />
          {this.state.showLayer1 && (
            <VectorLayer
              source={vector({
                features: new GeoJSON().readFeatures(geojsonObject, {
                  featureProjection: get("EPSG:3857"),
                }),
              })}
              style={FeatureStyles.MultiPolygon}
            />
          )}
          {this.state.showMarker && (
            <VectorLayer source={vector({
                features: this.state.features 
            })} />
          )}
        </Layers>
        <Controls>
          <FullScreenControl />
        </Controls>
      </Map>
    </div>
  );
}

使用像 React 这样的工具的主要优点之一是它只会刷新 render 方法中已更新其依赖数据的组件。有关详细信息,请参阅 this article

您的地图再次呈现这一事实表明地图或其子地图正在传递一段不断变化的数据。

根据您的代码,一种可能性是调用 OSM(),因为它是来自 OpenLayers API 的构造函数。 JavaScript 中的新 object/class 实例可能会导致数据重新呈现。