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



有没有内置的在react-router-dom v6中,返回BUT如果前一页不在应用程序的上下文中,则路由到根目录,从而到达,而不是从应用程序出去。.

示例:我从www.google.com冲浪到www.thing.com/thingy,这个页面(www.thing.com/thingy)上有一个go back按钮=>当我点击返回按钮时=>我被重定向到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;

最新更新