隨著前端應用的變得越來越複雜,單頁應用已經不能滿足我們的需求,因此使用路由來實現多頁面應用就顯得尤為重要。其中,React提供的react-router庫能夠輕鬆的進行頁面路由的管理,而其history API也提供了諸多方式用於頁面跳轉,其中history.push()方法就是最為常用的一種,本文將為大家詳細介紹在React中如何使用history.push()來實現頁面跳轉。
一、history.push()是什麼?
在React中使用路由實現頁面跳轉需要使用到history API,其中history.push()方法就是最常用的一種。history.push()實現的功能是將一個新地址加入到歷史地址記錄之中,以便在瀏覽器後退時重新回到該地址,同時顯示新增的地址內容,這樣就能實現頁面的跳轉操作。
history.push()的語法如下:
history.push(path, [state])
其中,path表示要跳轉的地址,state是一個可選參數,是一個JavaScript對象,可以在跳轉後新頁面中的this.props.location.state中獲取到,通常用於傳遞額外數據。
二、如何在React中使用history.push()實現頁面跳轉?
在React項目中,我們一般使用react-router-dom庫來實現路由功能。在使用history.push()方法之前,我們需要確保以下兩個前提條件:
1、在index.js文件中將App組件用BrowserRouter包裹起來,用於實現路由的監聽:
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root')
);
2、需要在當前組件中引入history對象,並在組件中使用withRouter高階函數進行包裹,使得路由相關的屬性可以被當前組件使用:
import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
class MyComponent extends Component {
handleClick = () => {
const { history } = this.props;
history.push('/newpage', { data: '額外的數據' });
};
render() {
return (
<button onClick={this.handleClick}>跳轉到新頁面</button>
);
}
}
export default withRouter(MyComponent);
在上述代碼中,我們首先引入了 withRouter 高階函數,這樣MyComponent組件就可以使用路由相關的屬性。handleClick函數中使用props中傳入的history.push()方法來進行頁面的跳轉,其中第一個參數是跳轉的目標地址,第二個參數是可以傳遞的額外數據。渲染時,我們將按鈕與handleClick函數相連接,點擊按鈕即可執行跳轉操作。
三、history.push()的注意事項
在使用history.push()方法中,我們需要注意以下幾點:
1、在使用history.push()方法跳轉頁面的時候,我們應該避免在生命周期函數中使用。因為在執行生命周期函數的時候,我們的 DOM 結構還未生成,此時如果執行跳轉操作就會導致錯誤。一般來說正確的方法是在componentDidMount中或者點擊事件中使用history.push()方法。
2、在頁面跳轉中我們可以使用history.goBack()方法回退到上一頁,只需要簡單的調用history.goBack()方法即可實現跳轉,如下所示:
import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
class MyComponent extends Component {
handleGoBack = () => {
const { history } = this.props;
history.goBack();
};
render() {
return (
<button onClick={this.handleGoBack}>回到上一頁</button>
);
}
}
export default withRouter(MyComponent);
3、在React中使用Redux的話,我們可以使用action creator 中的history.push()方法進行頁面跳轉操作,如下所示:
import { push } from 'connected-react-router';
function navigateTo(pathname, search = '') {
return dispatch => {
dispatch(push({
pathname,
search
}));
};
}
四、結語
在本文中,我們詳細介紹了在React中使用history.push()方法實現頁面跳轉的方法,也針對一些需要注意的事項進行了說明。希望通過本文的講解能夠讓大家更好的掌握React的路由功能,實現更加豐富的頁面表現。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/198325.html