What is withRouter for in react-router-dom?

后端 未结 4 1982
小鲜肉
小鲜肉 2020-12-02 04:56

I\'ve sometimes seen people wrap their components in withRouter when they are exporting them:

import { w         


        
4条回答
  •  半阙折子戏
    2020-12-02 05:40

    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. simply it connects component to the router.

    Not all components, especially the shared components, will have the access to such router's props. Inside its wrapped components, you would be able to access location prop and get more information like location.pathname or redirect the user to different url using this.props.history.push.

    Here's a complete example from their github page:

    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 
    You are now at {location.pathname}
    ; } } // Create a new component that is "connected" (to borrow redux // terminology) to the router. const ShowTheLocationWithRouter = withRouter(ShowTheLocation);

    More information could be found here.

提交回复
热议问题