你應該知道的react router 4(五)
阿新 • • 發佈:2018-09-21
parent 常用 training api 應該 urn 包裝 外部 prop
或許,你覺得我麻煩,明明一篇文章可以搞定的內容,非要寫幾篇。是不是正在吐槽我?沒關系,我的目的達到了。手動傲嬌( ̄? ̄)
然後,我們就要來聊一聊withRouter了。
我們都知道,當我在訪問路由配置文件中的組件,通常我們稱之為路由組件時,可以從他的props中訪問到路由對象。如,location。但是,沒有聲明在路由中的組件,通常我們稱之為非路由組件,比如路由組件中我們使用到的外部組件時,我們需要用到路由對象該怎麽辦呢?
在3.X中,我們要在非路由組件中使用history對象,需要手動引入history,就像這樣,
import createHistory from ‘history/createBrowserHistory‘ const history= createHistory()
或者,我們在路由組件中將獲取到的路由對象手動傳遞給外部組件。
<Parent>
<Child routeProps = {this.props.location} />
</Parent>
再或者,我們可以使用H5的history API。
window.location
但是4.X中我們可以不用那麽麻煩了,直接一個withRouter包裹你的外部組件,即可通過props訪問到location, router及history等對象。
就像這樣,
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> ) } } const ShowTheLocationWithRouter = withRouter(ShowTheLocation)
來自:https://reacttraining.com/react-router/web/api/withRouter
接著再來看, component.WrappedComponent
// MyComponent.js export default withRouter(MyComponent) // MyComponent.test.js import MyComponent from ‘./MyComponent‘ render(<MyComponent.WrappedComponent location={{...}} ... />)
它用於創建一個包裝組件上,通常用於測試。
wrappedComponnetRef這個函數的作用是refs獲取組件實例。
class Container extends React.Component { componentDidMount() { this.component.doSomething() } render() { return ( <MyComponent wrappedComponentRef={c => this.component = c}/> ) } }
你應該知道的react router 4(五)