【问题标题】:How to update URL with map coordinates?如何使用地图坐标更新 URL?
【发布时间】: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


【解决方案1】:

只需将新的 url 推送到历史堆栈,

window.history.pushState({/*empty state object*/}, "example name", "/`@${lat},${lng},${z}`");

更改网址而不导致浏览器加载新页面

查看documentation

【讨论】:

    【解决方案2】:

    我为自己建立的网站做了这件事。没有使用 react-router 而是使用我自己的小 url 解析器来更新 URL 并在页面加载时通知 redux url 参数。

    https://github.com/jbccollins/metro-monitor/blob/master/client/src/containers/app/index.js#L55

    这里是使用 onMoveEnd 调用它的地方 https://github.com/jbccollins/metro-monitor/blob/master/client/src/containers/MetroMap/index.js#L269

    请注意,我添加了一项检查,以确保您不会保存使用移动捏合缩放可能发生的小数缩放级别。这真的会混淆传单并导致我的应用程序崩溃。

    希望有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-21
      • 1970-01-01
      • 2017-05-26
      • 2013-05-22
      相关资源
      最近更新 更多