Link
,这将引发以下情况:Error: Invariant failed: You should not use <Link> outside a <Router>
[这让我感到困惑,因为Map
组件是App
组件的子组件,该组件被BrowserRouter
中的react-router-dom
包裹。
Map
组件:
import React, { Component } from 'react';
import { initalizeMap, getCenter, getZoom, addGeolocateButton, addMarkers, getMarkers } from '../helpers/mapbox';
export default class EventsMap extends Component {
state = { lng: 2.1700556, lat: 41.3869959, zoom: 11 };
onMapMove = () => this.setState({
lng: getCenter('lng', this.map),
lat: getCenter('lat', this.map),
zoom: getZoom(this.map),
});
renderMap = () => {
const { lng, lat, zoom } = this.state;
this.map = initalizeMap(lng, lat, zoom, this.mapContainer);
this.map.on('move', () => this.onMapMove());
addGeolocateButton(this.map);
const markers = getMarkers(this.props.events);
addMarkers(markers, this.map);
}
componentDidMount = () => this.renderMap();
render() {
return (
<div className='events-map'>
<div ref={(el) => this.mapContainer = el} className='mapContainer' />
</div>
);
}
}
[mapbox.js
帮助程序导入和addMarkers
声明:
import React from 'react'; import ReactDOM from 'react-dom'; import { Link } from 'react-router-dom'; import mapboxgl from 'mapbox-gl'; export const addMarkers = (markers, map) => { markers.features.forEach((marker) => { const el = document.createElement('div'); el.className = 'marker'; const { _id, name, place } = marker.properties; const markerDiv = document.createElement('div'); const markerContents = <div><Link to={`/events/${_id}`}><h3>{name}</h3></Link><p>{place}</p></div>; ReactDOM.render(markerContents, markerDiv); new mapboxgl.Marker(el) .setLngLat(marker.geometry.coordinates) .setPopup(new mapboxgl.Popup({ offset: 25 }) .setDOMContent(markerDiv)) .addTo(map); }) };
使用外部网址的锚点没有问题,例如:const markerContents = <div><a href={
https://google.com}><h3>{name}</h3></a><p>{place}</p></div>;
但是我需要对内部链接使用
Link
以避免重定向,重新加载等。Link
为什么不选择Router
上下文?
我正在使用带有标记的Mapbox GL JS映射在React(16)SPA上工作,并且我试图在每个标记弹出窗口中呈现一个链接,这将引发以下错误:错误:不变失败:您不应该使用
<Link>
获得react-router-dom
正常工作,而只是用Map
HoC包装了父withRouter
组件的导出,将this.props.history
传递到addMarkers
,并附加了一个事件侦听器到弹出内容并推送到历史记录对象onClick以便重定向:export const addMarkers = (markers, map, history) => {
markers.features.forEach((marker) => {
const onClick = (e) => {
const { _id } = marker.properties;
history.push(`/events/${_id}`);
}
const el = document.createElement('div');
el.className = 'marker';
const { name, place, rank } = marker.properties;
el.style.backgroundImage = `url(/markers/${rank + 1}.svg)`;
const popupContainer = document.createElement('div');
const popupContents = <div><button onClick={onClick}><h3>{name}</h3></button><p>{place}</p></div>;