reactRouter for react-router-dom是什么?

Lon*_*Rob 55 reactjs react-router

有时会看到人们在withRouter导出它们时将它们包装起来:

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

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

export default withRouter(Foo);
Run Code Online (Sandbox Code Playgroud)

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

Lon*_*Rob 103

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

<Route path="/movies" component={MoviesIndex} />
Run Code Online (Sandbox Code Playgroud)

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

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

render() {
  return (<Header />);
}
Run Code Online (Sandbox Code Playgroud)

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

要解决此问题,可以在withRouter导出时将标头组件包装在函数中:

export default withRouter(Header)
Run Code Online (Sandbox Code Playgroud)

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

  • 如[@msoliman的答案](/sf/answers/3963560261/)中所述,`withRouter`也可以访问`match`和`location`。如果接受的答案提到那将是很好的,因为重定向用户不是`withRouter`的唯一用例。否则,这很不错。 (7认同)

Muh*_*man 20

withRouter是一个更高阶的组件,它会在渲染时将最近路线的match,current locationhistoryprops传递给包装的组件。只需将组件连接到路由器即可。

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

这是他们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);
Run Code Online (Sandbox Code Playgroud)

这里可以找到更多信息。


小智 16

withRouter高阶组件允许您访问history对象的属性和最接近<Route>的匹配项。每当它呈现时,withRouter都会将 updated matchlocationhistoryprops 传递给包装的组件。

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);
Run Code Online (Sandbox Code Playgroud)