mai*_*n.m 4 javascript reactjs react-router-v4 react-router-dom
我在 React Router 上遇到了一些我似乎无法弄清楚的问题。它不会返回到访问的最后一页,而是返回它加载的第一页。这是一个例子。
索引.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>
Run Code Online (Sandbox Code Playgroud)
当您前往时/dashboard,您可以点击查看带您前往的游戏列表/games。然后,您可以单击游戏以查看它的单个视图,该视图会将您带到/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;
Run Code Online (Sandbox Code Playgroud)
小智 6
您可以通过goBack()在historyobject inside 中调用function来实现这一点withRouter()。
import React from 'react';
import { withRouter } from 'react-router-dom'
export default withRouter(({ history }) => {
return (
<div>
<button onClick={() => history.goBack()}>BACK</button>
</div>
)
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12510 次 |
| 最近记录: |