在react-router-dom中withRouter有什么用?

reactjs React.js

理查德十三Davaid

2020-03-13

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

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

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

export default withRouter(Foo);

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

第1534篇《在react-router-dom中withRouter有什么用?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

4个回答
null 2020.03.13

withRouter是一个高阶组件,它将传递最接近的路线以访问某些属性,如位置和道具的匹配,只有赋予组件位于组件中的属性,才能访问该属性

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

并且匹配和位置繁荣,以便能够更改位置并使用this.props.history.push,应该为每个组件属性提供该属性。必须提供,但是使用WithRouter时,可以访问位置并进行匹配,而无需添加属性历史记录可以访问方向,而无需为每个路径添加属性历史记录。

飞云西里神乐 2020.03.13

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

这里可以找到更多信息

null 2020.03.13

withRouter高阶组件使您可以访问history对象的属性和最接近<Route>的匹配项。withRouter将通更新matchlocationhistory道具给被包装的成分时,它呈现。

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);
理查德十三Davaid 2020.03.13

当您在应用程序中包含主页组件时,通常将其包装在这样的<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,这意味着标题现在可以重定向用户。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android