react-router-dom v6中如何返回到之前的路由



在早期版本中,我们可以返回到之前的路由使用.

history.goBack()

如何实现v6react-router-dom

?

试试这个方法

import { useNavigate } from 'react-router-dom';
function YourApp() {
const navigate = useNavigate();
return (
<>
<button onClick={() => navigate(-1)}>go back</button>
</>
);
}

in V6,

import { useNavigate } from 'react-router-dom';

function App() {
const navigate = useNavigate();

return (
<>
<button onClick={() => navigate(-2)}>Go 2 pages back</button>
<button onClick={() => navigate(-1)}>Go back</button>
<button onClick={() => navigate(1)}>Go forward</button>
<button onClick={() => navigate(2)}>Go 2 pages forward</button>
</>
);
}

以防有人像我一样来到这里,如果你不能导航回去(例如链接在新选项卡中打开),似乎没有任何方法可以验证react-router在v6中的历史。然而似乎你可以访问window.history.state,它有一个idx属性,如果你在历史堆栈的开始是零。

它可能有一些我没有碰到过的问题,但它对我来说是有效的:

import { useNavigate } from 'react-router-dom';
// ...
const navigate = useNavigate();
// ...
if (window.history.state && window.history.state.idx > 0) {
navigate(-1);
} else {
navigate('/', { replace: true }); // the current entry in the history stack will be replaced with the new one with { replace: true }
}

在旧版本的react-router-dom中存在函数pop

你可以这样联系他们:

const history = useHistory();
history.pop()

现在在v6中你可以使用函数useNavigate

const navigate = useNavigate();
navigate(-1) // you will go one page back
navigate(-2) // you will go two pages back

在react-router Links v6中还有另一种使用delta (number)的方法:

const BackButton = () => {
return (
<Link to={-1}>
Back
</Link>
);
};

不幸的是,在typescript中有一个类型错误,Link组件不接受数字,但仍然可以工作。

如果你想要返回或其他地方,你可以试试:

<button onClick={() => navigate(-1) || navigate('/dashboard')}>
Go back or Dashboard
</button>

我想补充的是,有时,存在一种情况,其中导航(-1)将导致错误的页面,例如在授权检查期间进行重定向。

import { useNavigate } from 'react-router-dom';
const navigate = useNavigate();
navigate(-1);

如果我们想显式地定义一个状态,我们有一个上一页,我们可以添加"from"属性。

import { useLocation, useNavigate } from 'react-router-dom';
const location = useLocation();
const navigate = useNavigate();
const currentPath = location.pathname;
navigate('/login', { state: { from: currentPath } });

在导航到登录页面之前,我们将路由状态设置为带有"from"属性,该属性等于当前路由。

在登录后加载页面时,我们首先检查是否有先前的路由存储在状态的"from"属性,很像只有一个级别的历史堆栈。

const state = location.state;
if (state?.from) {
// Redirects back to the previous unauthenticated routes
navigate(state?.from);
else {
navigate('/main-page');
}

如果"from"属性为false,则导航到默认页面。

同样,这是一种我们显式定义以前的路由而不是依赖于历史记录中最近的条目的解决方案。

import { useEffect } from "react";
import {useNavigate } from "react-router-dom";// react-router-dom v6 version 
const SecondComponent = () =>{
const navigate = useNavigate();

useEffect(() => {
navigate('/secondComponent')
},[]);
// note: we must have to to provide path like this one 
/*
<Routes>
<Route path="/" element={<FirstComponent/>} />
<Route path="/secondComponent" element={<SecondComponent />} />
</Routes>
*/
return(
<>
<h2 >this is Second page</h2>
</>
)
}
export  default SecondComponent;