快捷导航

react-router的withRouter方法是干嘛的,什么时候要用到?

react-router的withRouter方法是干嘛的,什么时候要用到?

免责声明:本内容仅代表回答者见解不代表本站观点,请谨慎对待。

版权声明:作者保留权利,不代表本站立场。

回复

使用道具 举报

参与会员1

首先withRouter可以用来给组件注入router相关的一些参数,比如:
```
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)

```
其次withRouter是专门用来处理数据更新问题的。在使用一些redux的的`connect()`或者mobx的`inject()`的组件中,如果依赖于路由的更新要重新渲染,会出现路由更新了但是组件没有重新渲染的情况。这是因为redux和mobx的这些连接方法会修改组件的`shouldComponentUpdate`。
座椅在使用withRouter解决更新问题的时候,一定要保证withRouter在最外层,比如`withRouter(connect(Component))`
回复

使用道具 举报

可能感兴趣的问答

发新帖
  • 微信访问
  • 手机APP