Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

react-router 学习笔记~ #50

Open
Samgao0312 opened this issue May 13, 2020 · 0 comments
Open

react-router 学习笔记~ #50

Samgao0312 opened this issue May 13, 2020 · 0 comments

Comments

@Samgao0312
Copy link
Owner

Samgao0312 commented May 13, 2020

API

withRouter

withRouter是 react-router 的一个高阶组件,可获取history。
render时会把match, location和history传入props。

在 react 中只有经过路由渲染的组件才拥有路由参数,例如:使用this.props.history.push('/a')跳转到对应路由的页面。而withRouter作用就是将路由参数传入this.props中,这样一来那些没有使用路由跳转的组件,也能够获取路由参数了。

⚠️注意:

withRouter组件有两种使用方法:(1)withRouter(App) (2)直接在组件上使用'@withRouter'。
使用@这种写法的话,需要babel-plugin-transform-decorators-legacy包。

npm install babel-plugin-transform-decorators-legacy --save-dev

还需要在packag文件中的babel中配置,具体实现方式可以查看react @装饰器相关文档。

{
    "plugins":[
        "transform-decorators-legacy"
    ]
}

通过 withRouter 高阶组件可以访问 history 对象的属性,以及最近的匹配项。每次渲染组件时(renders)时,withRouter都会将更新的匹配(match)、位置(location) 和 history props传递给包装组件(wrapped component)。

import React from "react";
import PropTypes from "prop-types";
import { withRouter } from "react-router";

// 显示当前路径名
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.
//创建一个 “连接(connected)” 到路由器的新组件(借用redux术语)。
const ShowTheLocationWithRouter = withRouter(ShowTheLocation);

重点:

withRouter 不像 React Redux 的 connect 那样订阅位置更改来进行状态更改。
而是在位置更改后从 组件传播出去后重新渲染。
这意味着 withRouter 不会在路由转换时重新呈现,除非其父组件重新呈现。

静态方法与属性
包装组件所有不是 react 的(no-react)特定的静态方法和属性自动复制到“已连接”组件。

Component.WrappedComponent

包装的组件在返回的组件上作为静态属性 WrappedComponent 公开,它可以用于隔离测试组件等。

// MyComponent.js
export default withRouter(MyComponent)

// MyComponent.test.js
import MyComponent from './MyComponent'
render(<MyComponent.WrappedComponent location={{...}} ... />)

wrappedComponentRef: func

该函数将作为ref prop传递给包装的组件。

class Container extends React.Component {
  componentDidMount() {
    this.component.doSomething();
  }

  render() {
    return (
      <MyComponent wrappedComponentRef={c => (this.component = c)} />
    );
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant