gpt4 book ai didi

javascript - React Router - 返回最后访问的页面,而不是默认组件

转载 作者:行者123 更新时间:2023-12-04 12:17:05 31 4
gpt4 key购买 nike

我在使用 React Router 时遇到了一些问题,我似乎无法弄清楚。它不会返回访问的最后一个页面,而是返回它加载的第一个页面。这是一个例子。

index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router } from 'react-router-dom';
import PrivateRoute from './utils/auth/PrivateRoute';
<Router>
<PrivateRoute exact path="/dashboard" component={DashboardView} />
<PrivateRoute exact path="/games" component={Games} />
<PrivateRoute
exact
path="/viewgame/:id*/"
component={SingleGameView}
/>
</Router>

当你去 /dashboard ,您可以点击查看游戏列表,带您前往 /games .然后,您可以单击一个游戏来查看它的单一 View ,这会将您带到 /viewgame/:id*
像这样:/dashboard ->/games ->/viewgame/:id*

当你点击一个游戏并被带到 /viewgame/ ,然后决定在浏览器中单击返回,它带我回到 /dashboard而不是带我回到/games。它跳过了最后访问的页面,并带我回到第一个加载的页面。我可以通过设置我自己的“单击返回”按钮将某人送回路线,但我需要浏览器实际的后退和前进按钮来执行此操作。
PrivateRoute是我设置的一个 HOC,用于检查以确保访问路由的用户是否经过身份验证。否则它们将被引导。万一这可能是该组件的问题:
import React from 'react';
import { Route, Redirect } from 'react-router-dom';

//Utils - Auth
import { userAuth } from '../../../authentication/authentication';
const { isAuthenticated } = userAuth;

//Checks if a user isAuthenticated. If so, it renders the passed in secure component. If not, it renders a redirect to /signin
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route
{...rest}
render={props =>
isAuthenticated() ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: '/signin',
state: { from: props.location }
}}
/>
)
}
/>
);

export default PrivateRoute;

这是渲染组件时 PrivateRoute Prop 的快照: enter image description here

最佳答案

您可以通过调用 goBack() 来实现此目的。 history中的函数内部对象 withRouter() .

import React from 'react';
import { withRouter } from 'react-router-dom'

export default withRouter(({ history }) => {
return (
<div>
<button onClick={() => history.goBack()}>BACK</button>
</div>
)
});

关于javascript - React Router - 返回最后访问的页面,而不是默认组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58613164/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com