[英]How to redirect page after login using react-router-dom?
晚上好。 我在尝试正确重定向用户时遇到了一些问题,如果用户未登录。然后网站将用户直接重定向到登录页面,用户登录后。他们被重定向到一个页面,但是,每当尝试使用任何链接直接访问页面。 它总是在登录后重定向到同一页面。
index.js
ReactDOM.render(
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>,
document.getElementById("root")
);
App.js
...
let routes = (
<Switch>
<Route path="/" exact component={Login} />
<Redirect to="/" />
</Switch>
);
if (props.isUserAuth) {
routes = (
<Switch>
<Route
path="/dashboard/"
render={() => (
<Suspense fallback={<LoadingScreen />}>
<Dashboard />
</Suspense>
)}
/>
<Redirect to="/dashboard/" />
</Switch>
);
}
return ({routes});
dashboard.js
<div className={classes.offset}>
<Switch>
<Route exact path="/dashboard/quotes" component={Quotes} />
<Route path="/dashboard/quotes/addquote" component={AddQuote} />
<Route path="/dashboard/quotes/:id" component={EditQuote} />
...
<Redirect exact from="/dashboard/" to="/dashboard/quotes" />
<Route component={NotFound} />
</Switch>
</div>
问题
App.js 实际上将用户重定向到“/dashboard/”,它总是将用户重定向到“/dashboard/quotes”,无论用户是否访问不同的链接,如您在上面的代码中看到的那样。 无论用户是否登录,登录组件都会正确地重定向用户。 但是,如果已经登录的用户试图直接访问链接(例如:“/dashboard/something/id”),无论如何他们总是被重定向到“/dashboard/quotes”。
我在不允许直接链接访问的index.js
文件中使用组件(根据这个答案)将其更改为 HashRouter 后,它似乎已经解决了问题(尽管 URL 中有#)。 但是根据文档,它说我们应该只使用它来支持旧版浏览器,所以我不确定它是否是正确的答案。
我不确定如何解决这个问题。 有人可以帮帮我吗? 我真的很感谢帮助和时间!
解决方案
原来我做错了路由。 重定向在某个时间点工作正常,但按原样使用 Switch 时,它没有正确更改。 这是我的解决方案:
app.js
let routes = (
<Switch>
<Route component={Login} />
</Switch>
);
if (props.isUserAuth) {
routes = (
<Switch>
<Route
path="/"
render={() => (
<Suspense fallback={<LoadingScreen />}>
<Dashboard />
</Suspense>
)}
/>
</Switch>
);
}
dashboard.js
<Switch>
<Route exact path="/quotes" component={Quotes} />
<Route path="/quotes/addquote" component={AddQuote} />
<Route path="/quotes/:id" component={EditQuote} />
...
{/* Home Route */}
<Route exact path="/" component={Quotes} />
<Route component={NotFound} />
</Switch>
我以前遇到过这个问题,这对我有用。
这是在 react 的登录组件中
if(state == logged in){
<Redirect to="/dashboard/quotes" />
}
如果有用户立即重定向,请检查登录的 state
如果您不想维护额外的 state 变量,也可以这样做。
function Component() {
const history = useHistory();
// pass this function to the event handler.
function doSomething() {
history.push('/dashboard/quotes')
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.