我已经检查了the following post,虽然它提供了几种不同的解决方案,而不是解决我的问题。
使用react-router V4我需要以编程方式从我的树内部组件中导航,将无法访问路由器道具(历史记录,网址,参数等)。这种做法最直接的方式是什么?
答案 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
使用的location
,match
和react-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找到更多信息