1 回答
TA贡献2条经验 获得超6个赞
首先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 (
<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)
```
其次withRouter是专门用来处理数据更新问题的。在使用一些redux的的`connect()`或者mobx的`inject()`的组件中,如果依赖于路由的更新要重新渲染,会出现路由更新了但是组件没有重新渲染的情况。这是因为redux和mobx的这些连接方法会修改组件的`shouldComponentUpdate`。
座椅在使用withRouter解决更新问题的时候,一定要保证withRouter在最外层,比如`withRouter(connect(Component))`
添加回答
举报