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))`
添加回答
舉報