【发布时间】:2018-11-15 19:07:06
【问题描述】:
我的 React 应用上有一张 Leaflet 地图,我想在地图移动时使用位置信息(纬度、经度和缩放)动态更新 URL。
类似:app.com/lat,lng,z/myroutes
此外,lat,lng,z 应该具有默认值,以便应用可以从 app.com 启动并重定向。
Leaflet 有一个名为 onMoveend 的事件监听器,它为我提供我想要的信息。问题是如何将它传递给我的路由器,以便它更新 URL 和应用程序内部链接。
我正在为路由使用 react-router v4。
我已经尝试创建一个自定义历史对象,该对象具有附加到状态的基本名称属性,然后将其传递给路由器。它有效(在更新 URL 方面 - 在本例中为基本名称),但应用程序上的导航崩溃并且控制台显示“您无法更改路由器历史记录”。
这是更新 URL 的组件(this.props.map 来自 Redux 存储):
componentDidUpdate(prevProps) {
if (this.props.map !== prevProps.map) {
const { lat, lng, z } = this.props.map
this.setState({ lat, lng, z })
}
}
render() {
const { lat, lng, z } = this.state
if (lat && lng && z) {
const history = createBrowserHistory({
basename: `@${lat},${lng},${z}`
})
return (
<Router history={history}>
<Main>
<Switch>
<Route exact path='/farms' component={FarmsList} />
<Route exact path='/farms/new' component={NewFarm} />
<Redirect from='*' to='/farms' />
</Switch>
</Main>
</Router>
)
} else {
...
}
}
【问题讨论】:
-
您是否尝试过使用
shouldComponentUpdate()?向我们展示您如何尝试更改位置,如minimal reproducible example -
从问题不清楚...我想这就是你想要的?
history.push({ pathname: '/', search: new URLSearchParams({ lat: '10', lng: '20', z: 'whatever...' }).toString(), }); -
更新了问题正文。我不确定 history.push 是否是解决方案,因为更改必须在基本名称中。有一种方法可以在不设置基本名称的情况下解决问题吗?我的意思是,也许将 lat,lng,z 设置为 /:params?类似于:
标签: javascript reactjs react-router