繁体   English   中英

React-router-dom (v6) go 仅在应用程序内返回

[英]React-router-dom (v6) go back only within application

react-router-dom v6 中是否有内置方法,可以通过 go 返回上一页,如果上一页不在应用程序的上下文中,则路由到根目录,因此不会超出申请

示例:我从www.google.com浏览到www.thing.com/thingy ,此页面 ( www.thing.com/thingy ) 上有一个go back按钮 => 当我点击 go 后退按钮时 =>我被重定向到www.google.com而不是想要的行为重定向到www.thing.com 示例页面的模型。

我已经尝试了几种实现并通过文档进行了搜索,但找不到解决此问题的内置方法。 据我所知,没有办法。 但是,如果不是,我可以定制一些东西来解决我的问题。

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

我通过跟踪历史来解决它。

如果用户还没有访问过该页面,我会将他们重定向到主页。 否则将他们重定向到上一页。

 import { useEffect } from 'react'; import { createContext, useMemo, useState } from 'react'; import { useLocation } from 'react-router-dom'; export const LocationHistoryContext = createContext({}); const LocationHistoryProvider = ({ children }) => { const [locationHistory, setLocationHistory] = useState( new Set(), ); const location = useLocation(); useEffect(() => { // if pathname has changed, add it to the history let path = location.pathname.match(/^\/([^/])*/)[0]; setLocationHistory((prev) => new Set([path, ...prev])); }, [location.pathname, location]); const context = useMemo(() => { return { /* if the user has visited more than one page */ hasHistory: locationHistory.size > 1, }; }, [locationHistory]); return ( < LocationHistoryContext.Provider value = {context}> { children } </LocationHistoryContext.Provider> ); }; export default LocationHistoryProvider;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM