一、初識this.props.history
this.props.history是React Router的一個重要組成部分,它允許我們對瀏覽器的歷史記錄進行操作。
import { useHistory } from 'react-router-dom';
function Example() {
const history = useHistory();
function handleClick() {
history.push('/home');
}
return (
);
}
二、導航與路由
在一個React應用程序中,當你點擊一個鏈接或訪問一個URL時,你的應用程序需要知道如何響應該事件並顯示相應的頁面。這就是React Router庫的作用,它在瀏覽器中使用標準的path,route和URL來組織和渲染應用程序的UI。
this.props.history提供了許多函數來導航你的應用程序,例如:history.push()
、history.replace()
、history.goBack()
等等。這些函數可以讓你在React的組件中輕鬆地進行路由跳轉、頁面跳轉等操作。
三、history.push()
history.push()是非常常用的路由操作。它將一個新的entry添加到歷史記錄中,然後在對應的路由路徑中呈現對應的組件。下面是history.push()的一個示例:
import React from 'react';
import { withRouter } from 'react-router-dom';
class Sample extends React.Component {
constructor(props) {
super(props);
this.onClick = this.onClick.bind(this);
}
onClick() {
this.props.history.push('/home');
}
render() {
return (
);
}
}
export default withRouter(Sample);
四、history.replace()
history.replace()與history.push()的主要區別在於,它不會在瀏覽器歷史記錄中添加一個新的entry。相反,它將當前頁面替換為新的路徑和組件。下面是history.replace()的一個示例:
import React from 'react';
import { withRouter } from 'react-router-dom';
class Sample extends React.Component {
constructor(props) {
super(props);
this.onClick = this.onClick.bind(this);
}
onClick() {
this.props.history.replace('/home');
}
render() {
return (
);
}
}
export default withRouter(Sample);
五、history.goBack()
history.goBack()用於在歷史記錄中後退一個entry。這個函數在實現“後退”按鈕時經常使用。下面是history.goBack()的一個示例:
import React from 'react';
import { withRouter } from 'react-router-dom';
class Sample extends React.Component {
constructor(props) {
super(props);
this.onClick = this.onClick.bind(this);
}
onClick() {
this.props.history.goBack();
}
render() {
return (
);
}
}
export default withRouter(Sample);
六、history.push()和history.replace()的區別
history.push()和history.replace()的主要區別在於它們如何對待歷史記錄。push()方法將在歷史記錄中添加一個新的entry,而replace()方法將替換當前的entry。
如果你從一個頁面跳轉到另一個頁面,你可能希望使用push()方法。但是,如果你是在處理一個表單提交或者需要重定向到另一個頁面時,你可能會使用replace()方法。因為如果你只是在瀏覽器中使用push()方法,當用戶單擊瀏覽器的後退按鈕時,他們可能會回到前一個表單提交或重定向到的頁面。
七、總結
this.props.history可以讓我們輕鬆實現React Router的導航和路由操作。這篇文章詳細地介紹了history.push()、history.replace()、history.goBack()等常用的方法,並且解釋了它們之間的區別。了解這些方法非常重要,因為它們會影響你的應用程序如何處理瀏覽器中的歷史記錄。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/192716.html