react-router-dom 中的 withRouter 是什么? [英] What is withRouter for in react-router-dom?
问题描述
我有 有时看到人们在导出组件时将其组件包装在 withRouter
中:
I've sometimes seen people wrap their components in withRouter
when they are exporting them:
import { withRouter } from 'react-router-dom';
class Foo extends React.Component {
// ...
}
export default withRouter(Foo);
这是干什么用的,什么时候用?
What is this for, and when should I use it?
推荐答案
当你在你的应用中包含一个主页面组件时,它通常被包裹在一个
组件中,如下所示:
When you include a main page component in your app, it is often wrapped in a <Route>
component like this:
<Route path="/movies" component={MoviesIndex} />
通过这样做,MoviesIndex
组件可以访问 this.props.history
,因此它可以使用 this.props.history.push<重定向用户/代码>.
By doing this, the MoviesIndex
component has access to this.props.history
so it can redirect the user with this.props.history.push
.
某些组件(通常是页眉组件)出现在每个页面上,因此没有包含在
中:
Some components (commonly a header component) appear on every page, so are not wrapped in a <Route>
:
render() {
return (<Header />);
}
这意味着标头无法重定向用户.
This means the header cannot redirect the user.
为了解决这个问题,header 组件可以被包裹在一个 withRouter
函数,无论是在导出时:
To get around this problem, the header component can be wrapped in a withRouter
function, either when it is exported:
export default withRouter(Header)
这使 Header
组件可以访问 this.props.history
,这意味着标题现在可以重定向用户.
This gives the Header
component access to this.props.history
, which means the header can now redirect the user.
这篇关于react-router-dom 中的 withRouter 是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!