Ham*_*eed 3 reactjs react-router react-router-dom
在早期版本中,我们可以使用history返回到之前的路线。
history.goBack()
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点与V6的反应路由器-DOM?
San*_*eph 56
在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>
</>
);
}
Run Code Online (Sandbox Code Playgroud)
Gee*_*Gee 44
2023 年 12 月更新:
看来history.state.idx方法不再有效,目前可以使用history.length来实现,如下所示:
if (window.history?.length) {
router.back();
} else {
router.replace(href || "/");
}
Run Code Online (Sandbox Code Playgroud)
如果您支持旧系统,则将两者合并可能会有所帮助,如下所示:
if (window.history?.length || window.history.state?.idx) {
router.back();
} else {
router.replace(href || "/");
}
Run Code Online (Sandbox Code Playgroud)
原来的:
以防万一有人像我一样尝试向后导航或导航到其他地方(如果您无法向后导航(例如在新选项卡中打开的链接)),似乎没有任何方法可以使用反应路由器验证历史记录在 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 }
}
Run Code Online (Sandbox Code Playgroud)
小智 18
在旧版本的react-router-dom中存在pop函数
您可以通过以下方式联系他们:
const history = useHistory();
history.pop()
Run Code Online (Sandbox Code Playgroud)
现在在 v6 中你可以使用函数 useNavigate
const navigate = useNavigate();
navigate(-1) // you will go one page back
navigate(-2) // you will go two pages back
Run Code Online (Sandbox Code Playgroud)
Ped*_*nha 10
试试这个方法
import { useNavigate } from 'react-router-dom';
function YourApp() {
const navigate = useNavigate();
return (
<>
<button onClick={() => navigate(-1)}>go back</button>
</>
);
}
Run Code Online (Sandbox Code Playgroud)
Ste*_*e L 10
在react-router Links v6中还有另一种使用增量(数字)的方法:
const BackButton = () => {
return (
<Link to={-1}>
Back
</Link>
);
};
Run Code Online (Sandbox Code Playgroud)
不幸的是,打字稿中存在类型错误,链接组件不接受数字,但它仍然有效。
| 归档时间: |
|
| 查看次数: |
1429 次 |
| 最近记录: |