最近在開發react的項目中,很多地方都是使用組件式的跳轉方式,但是怎么樣使用js去控制頁面的跳轉呢?
withRouter
withRouter 是一個高階組件,把 match,location,history 三個對象注入到組件的 props 中。這是一個非常實用的函數,下面以四個小例子闡述它的用法。
1.與 redux 的 connect 配合
在項目中使用了 redux 來管理數據,當數據沒有變化時,組件也就不會重新渲染。假設在組件中某個 Route 組件並未被渲染,數據也未發生變化,即便當前頁面的鏈接發生了變化,也不會有任何的路由匹配該鏈接。因為這時候 Route 組件還是未被渲染!如何知道鏈接變化了呢?這時候就需要 withRouter 了。
import { withRouter } from 'react-router-dom' export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Component))
2.頁面的跳轉
React Router 提供了 Link,NavLink 與 Redirect 組件來控制頁面的跳轉。但是我在一個 Button 的點擊事件中控制頁面的跳轉,這幾個組件就無法使用了。這里,或許你會想到使用 location 對象。
// 錯誤的方式!!! location.href = '/article'
這種方式可行,但不正確。如果先前使用的 BrowserRouter 變成 HashRouter 的話,這種方式就失效了。withRouter 封裝的組件中的 props 包含 history,通過 history 對象來控制頁面的跳轉。history 對象有 push,replace 與 go 等方法,調用這些方式實現頁面的跳轉。
class Comoponent extends React.Component { handleClick () { this.props.history.push('/article') } } export default withRouter(Component)