react-router-dom 中的 withRouter 是什么?

新手上路,请多包涵

有时看到 人们在导出组件时将组件包装在 withRouter 中:

 import { withRouter } from 'react-router-dom';

class Foo extends React.Component {
  // ...
}

export default withRouter(Foo);

这是做什么用的,我应该什么时候使用它?

原文由 LondonRob 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 783
2 个回答

当您在应用程序中包含主页组件时,它通常被包装在 <Route> 组件中,如下所示:

 <Route path="/movies" component={MoviesIndex} />

通过这样做, MoviesIndex 组件可以访问 this.props.history 因此它可以使用 this.props.history.push 重定向用户。

某些组件(通常是标题组件)出现在每个页面上,因此不包含在 <Route> 中:

 render() {
  return (<Header />);
}

这意味着标头无法重定向用户。

为了解决这个问题,可以将标头组件包装在 withRouter 函数中,或者在导出时:

 export default withRouter(Header)

这使 Header 组件可以访问 this.props.history ,这意味着标头现在可以重定向用户。

原文由 LondonRob 发布,翻译遵循 CC BY-SA 4.0 许可协议

withRouter is a higher order component that will pass closest route’s match , current location , and history props to the wrapped component whenever it renders .只是它将组件连接到路由器。

并非所有组件,尤其是共享组件,都可以访问此类路由器的 props。在其包装的组件中,您将能够访问 location prop 并获取更多信息,例如 location.pathname 或使用 this.props.history.push 将用户重定向到不同的 url

这是来自他们的 github 页面的完整示例:

 import React from "react";
import PropTypes from "prop-types";
import { withRouter } from "react-router";

// A simple component that shows the pathname of the current location
class ShowTheLocation extends React.Component {
  static propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  };

  render() {
    const { match, location, history } = this.props;

    return <div>You are now at {location.pathname}</div>;
  }
}

// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
const ShowTheLocationWithRouter = withRouter(ShowTheLocation);

可以在 此处 找到更多信息。

原文由 Muhammad Soliman 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进