我有一个主要的 React 组件(整个页面),其中包含几个其他 UI 项目。其中一个 UI 项目是 OpenLayers map 。另一个组件是一个文本字段,其中包含当前鼠标指针位置的纬度和经度。
我希望只要鼠标指针在 map 上移动,文本字段就会更新。在我的代码的当前状态下,这是有效的。
问题是每次鼠标移动并且我更新纬度/经度的 react 状态值(按预期在文本字段中呈现)时, map 都会重新呈现。这看起来很糟糕,因为每次开始加载 map 图 block 时 map 都会闪烁。
所以我有鼠标的纬度/经度位置,但我无法让 map 不闪烁/断断续续/频闪。
有没有办法从 map 组件中获取鼠标事件,并将其发送到同一屏幕上的另一个组件,而不会导致 render 方法每次都重新绘制 map ?或者 React 是这个项目的错误工具?
请注意,我使用的是 React Redux处理一些状态值,例如 map 对象。我所有的子组件都是 React 函数式组件,但页面的主要组件是 React 类组件。
如果有帮助,我会像这样在 map 上设置鼠标监听器:
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 这样的工具的主要优点之一是它只会刷新渲染方法中的组件,这些组件已经更新了它们的依赖数据。参见 this article获取更多信息。
您的 map 再次呈现这一事实表明 map 或其子 map 正在传递一段不断变化的数据。
根据您的代码,一种可能性是调用 OSM()
,因为它是来自 OpenLayers API 的构造函数。 JavaScript 中的新对象/类实例可能会导致数据重新呈现。
关于reactjs - 如何强制一个 react 组件不重新渲染?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68365311/