代码之家  ›  专栏  ›  技术社区  ›  LondonRob

什么是withRouter for in-react router dom?

  •  3
  • LondonRob  · 技术社区  · 7 年前

    我已经 sometimes seen 人们把他们的组件包起来 withRouter 当他们在导出它们时:

    import { withRouter } from 'react-router-dom';
    
    class Foo extends React.Component {
      // ...
    }
    
    export default withRouter(Foo);
    

    这是做什么用的?我什么时候用?

    1 回复  |  直到 7 年前
        1
  •  202
  •   LondonRob    7 年前

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

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

    通过这样做 MoviesIndex 组件可以访问 this.props.history this.props.history.push .

    有些组件(通常是页眉组件)出现在每一页上,因此没有包装在 < :

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

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

    withRouter 函数,在导出时:

    export default withRouter(Header)
    

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

        2
  •  47
  •   Muhammad Soliman    6 年前

    withRouter match ,当前 location history 无论何时呈现包装的组件,都将其作为支柱。它只需将组件连接到路由器。

    并不是所有的组件,特别是共享组件,都可以访问这种路由器的道具。在其封装的组件中,您可以访问 位置 支持并获取更多信息 location.pathname this.props.history.push .

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

    可以找到更多信息 here

        3
  •  10
  •   Gideon Kitili    6 年前

    withRouter history 对象属性和最近的 <Route> 的匹配。 match , location ,和 历史 无论何时呈现包装的组件,都将其作为支柱。

    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);
    
        4
  •  0
  •   Mohammed_Alreai    6 年前

    <Route to="/app" component={helo} history ={history} />
    

    而同样的匹配和位置繁荣可以改变位置和使用这个。道具。历史.push它应该为每个组件提供属性必须提供,但是当与router一起使用时,它可以访问位置和匹配而不需要添加属性历史记录它可以访问方向而不必为每个路由添加属性历史。