React Router V4 (react-router-dom) 以编程方式在树的深处导航
React Router V4 (react-router-dom) navigate programatically deep in the tree
我检查了 ,虽然它提供了几个不同的解决方案,但没有一个能解决我的问题。
使用 react-router V4 我需要以编程方式从我的树内部深处的组件导航,不会 访问路由器道具传递(历史,url,参数, ETC。)。最直接的方法是什么?
最直接的方法是像这样将历史移动到单独的文件中
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',
})
}
...
您还需要确保将新的历史记录传递给路由器以使其正常工作
树中的任何组件,无论其深度如何,都可以访问 react-router
使用的 history
、location
和 match
属性。为此,您必须将组件包装在 react-router
.
提供的 withRouter
HOC 中
代码:
//other imports
import {withRouter} from 'react-router-dom'
//define component MyComponent here
export default withRouter(MyComponent);
在上面定义的 MyComponent 中,您可以访问 history
道具并使用 this.props.history.push(newURL);
重定向到任何新的 url 您可以在 https://reacttraining.com/react-router/web/api/withRouter[= 找到更多信息20=]
我检查了
使用 react-router V4 我需要以编程方式从我的树内部深处的组件导航,不会 访问路由器道具传递(历史,url,参数, ETC。)。最直接的方法是什么?
最直接的方法是像这样将历史移动到单独的文件中
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',
})
}
...
您还需要确保将新的历史记录传递给路由器以使其正常工作
树中的任何组件,无论其深度如何,都可以访问 react-router
使用的 history
、location
和 match
属性。为此,您必须将组件包装在 react-router
.
withRouter
HOC 中
代码:
//other imports
import {withRouter} from 'react-router-dom'
//define component MyComponent here
export default withRouter(MyComponent);
在上面定义的 MyComponent 中,您可以访问 history
道具并使用 this.props.history.push(newURL);
重定向到任何新的 url 您可以在 https://reacttraining.com/react-router/web/api/withRouter[= 找到更多信息20=]