React Router V4(react-router-dom)以编程方式深入导航到树中

时间:2017-10-23 23:55:53

标签: reactjs react-router react-router-v4

我已经检查了the following post,虽然它提供了几种不同的解决方案,而不是解决我的问题。

使用react-router V4我需要以编程方式从我的树内部组件中导航,无法访问路由器道具(历史记录,网址,参数等)。这种做法最直接的方式是什么?

2 个答案:

答案 0 :(得分:1)

最直接的方法是将历史记录移动到单独的文件中,如此

history.js

import createHistory from 'history/createBrowserHistory'
const history = createHistory()
export default history

然后在任何其他组件中:

import history from 'path/to/history.js'

...
someFoo(){
  history.push({
    pathname: '/new/url',
  })
}
...

您还需要确保将新历史记录传递给路由器以使其正常工作

答案 1 :(得分:1)

树中的任何组件,无论其深度如何,都可以访问history使用的locationmatchreact-router道具。为此,您必须将组件包装在withRouter提供的react-router HOC中。

代码:

//other imports
import {withRouter} from 'react-router-dom'

//define component MyComponent here

export default withRouter(MyComponent);

在上面定义的MyComponent中,您可以使用history访问this.props.history.push(newURL);道具并重定向到任何新网址。您可以在https://reacttraining.com/react-router/web/api/withRouter找到更多信息