What is withRouter for in react-router-dom?

后端 未结 4 1984
小鲜肉
小鲜肉 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:42

    withRouter higher-order component allows you to get access to the history object’s properties and the closest 's match. withRouter will pass updated match, location, and history props to the wrapped component whenever it renders.

    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);

提交回复
热议问题