2016-03-07 18 views
1

我想訪問當前的位置路徑(比如/ home),而不使用某些比較邏輯的歷史鍵。如何訪問反應路由器2上的當前散列位置?

我怎樣才能從hashHistory訪問它反應路由器2

此外,我怎麼能訪問以前的路徑?

+0

你想讀的URL哈希?那麼'window.location.hash'呢? – Andreyco

+0

當我使用location.hash我得到反應的鑰匙隨着散列 –

回答

3

您可以從location道具路線組件獲得當前路徑。從您的路徑組件的this.props.location

訪問的位置。如果 您希望在樹中更深入,則可以使用您的應用使用的任何 約定來使道具從高到低。一個 選擇是提供它上下文自己:

// V2.0.x中常量RouteComponent = React.createClass({
childContextTypes:{ 位置:React.PropTypes.object},

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

看一看here

爲了獲得當前的路徑,你可以只使用location.pathname。訪問路徑

+0

你能提供一些關於你想達到什麼的細節?另外,你是否需要在路由組件之外訪問這個?使用'location.pathname'是訪問位置路徑的官方方式,但通常有一些不受支持的非官方方式,取決於你想要做什麼:-) –

+0

我需要訪問路由的當前路徑。像localhost:9000 /#/ home。 我想'家'來比較它。反應的問題是,當我使用location.hash時,我得到了反應鍵,而location.pathname給我/所有的時間 –

+0

這很奇怪。沒有看到代碼就很難找出問題。我在codepen上創建了[一個小例子](http://codepen.io/alexchiri/pen/bpVXbd)。 'MainLayout'映射到'/'並在其內部顯示子節點'Home'和'UserList'。 'UserList'映射到'/ users'並在裏面顯示子'User'。 'User'映射到'/ users /:id',並沒有任何子節點。在這些組件的渲染方法中,我會顯示來自其道具的'location.pathname'。正如你可以注意到的那樣,當導航到一個孩子時,甚至它的宿主父母的'location.pathname'也被改變了。 –

1

的一種方式是經由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() 
相關問題