【问题标题】:How can i access the current hash location on react router 2?如何访问反应路由器 2 上的当前哈希位置?
【发布时间】:2016-03-07 12:23:01
【问题描述】:

我想在没有历史键的情况下访问当前位置路径(如 /home)以进行一些比较逻辑。

如何从反应路由器 2 中的 hashHistory 访问它。

另外,我怎样才能访问以前的路径?

【问题讨论】:

  • 你想读取 URL 哈希吗? window.location.hash呢?
  • 当我使用 location.hash 时,我会得到反应键和哈希

标签: reactjs react-router


【解决方案1】:

您可以从路由组件的location 属性中获取当前路径名。

从 Route 组件的 this.props.location 访问位置。如果 你想把它放在树的更深处,你可以使用任何东西 你的应用程序从高到低获取道具的约定。一 选项是自己在上下文中提供它:

// v2.0.x const RouteComponent = React.createClass({
childContextTypes:{ 位置:React.PropTypes.object },

getChildContext() { 返回{位置:this.props.location}}})

看看here

要获取当前路径,您可以使用location.pathname

【讨论】:

  • 您能否详细说明您想要实现的目标?另外,您是否需要在路由组件之外访问它?使用location.pathname 是获取位置路径的官方方式,但通常有一些不受支持的非官方方式,取决于您想要做什么:-)
  • 我需要访问当前路由的路径。像 localhost:9000/#/home。我想用“家”来比较它。 react 的问题在于,当我使用 location.hash 时,我得到了 react 键,而 location.pathname 一直给我 /
  • 这很奇怪。不看代码很难找出问题所在。我在 codepen 上创建了a small exampleMainLayout 映射到 / 并在其中显示子 HomeUserListUserList 映射到 /users 并在里面显示子 UserUser 映射到 /users/:id 并且没有任何子级。在每个组件的渲染方法中,我从它们的道具中显示location.pathname。正如您所注意到的,当导航到一个孩子时,甚至其托管父级的location.pathname 也发生了变化。
  • 即使你得到这个工作,我想这不是你想要的,因为pathname 返回完整路径,你可能只对最后一点感兴趣,但这是一个开始: -) 希望它可以帮助您走得更远,如果您有任何问题,请告诉我。
【解决方案2】:

访问路径的一种方法是通过来自反应组件的this.props.location

import React from 'react'
import { render } from 'react-dom'
import { browserHistory, Router, Route, Link } from 'react-router'

class Child extends React.Component {
  render() {
    let location = this.props.location
    return (
      <div>
        <h1>Child Component</h1>
        <p>{location.pathname}</p>
      </div>
    )
  }
}

class App extends React.Component {
  render() {
    return (
      <div>
            {this.props.children}
      </div>
    )
  }
}

render((
  <Router history={browserHistory}>
    <Route path="/" component={App}>
      <Route path="child" component={Child} />
    </Route>
  </Router>
), document.getElementById('example'))

如果您想通过历史记录收听当前位置的变化,另一种方式 -

import { createHistory } from 'history'

let history = createHistory()

// Listen for changes to the current location. The
// listener is called once immediately.
let unlisten = history.listen(function (location) {
  console.log(location.pathname)
})

// When you're finished, stop the listener.
unlisten()

【讨论】:

    猜你喜欢
    • 2017-03-23
    • 1970-01-01
    • 2019-04-25
    • 1970-01-01
    • 2018-09-04
    • 2018-10-03
    • 1970-01-01
    • 2021-04-25
    • 2017-11-08
    相关资源
    最近更新 更多