1 回答

TA貢獻(xiàn)2條經(jīng)驗(yàn) 獲得超6個(gè)贊
首先withRouter可以用來(lái)給組件注入router相關(guān)的一些參數(shù),比如:
```
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是專門用來(lái)處理數(shù)據(jù)更新問題的。在使用一些redux的的`connect()`或者mobx的`inject()`的組件中,如果依賴于路由的更新要重新渲染,會(huì)出現(xiàn)路由更新了但是組件沒有重新渲染的情況。這是因?yàn)閞edux和mobx的這些連接方法會(huì)修改組件的`shouldComponentUpdate`。
座椅在使用withRouter解決更新問題的時(shí)候,一定要保證withRouter在最外層,比如`withRouter(connect(Component))`
添加回答
舉報(bào)