gpt4 book ai didi

javascript - 如果用户登录使用 React 路由器重定向到仪表板?

转载 作者:行者123 更新时间:2023-11-30 11:22:18 24 4
gpt4 key购买 nike

我正在尝试实现重定向解决方案。如果用户已经登录并尝试访问主页(所有人可见),我想重定向到仪表板(仅对登录用户可见)。

我目前的解决方案:

export const PublicRoute = ({ auth, ...props }) => {
const isAllowed = auth.isLoggedIn();
return isAllowed
? <Redirect to="/dashboard" />
: <Route {...props} />;
};

用法:

<PublicRoute
auth={{ isLoggedIn: () => AuthService.isLoggedIn() }}
path="/"
component={Main}
/>

私有(private)路由组件:

export const ProtectedRoute =  ({ auth, ...props }) => {
const isAllowed = auth.isLoggedIn();
return isAllowed
? <Route {...props} />
: <Redirect to="/login" />;
};

但是,当执行此操作时,我收到以下警告:

Warning: You tried to redirect to the same route you're currently on: "/dashboard"

路线:

<Provider store={store}>
<Router history={History}>
<Switch>
<PublicRoute
auth={{ isLoggedIn: () => AuthService.isLoggedIn() }}
exact={true}
path="/"
component={Homepage}
/>

<PublicRoute
auth={{ isLoggedIn: () => AuthService.isLoggedIn() }}
path="/login"
component={Login}
/>

<ProtectedRoute
auth={{ isLoggedIn: () => AuthService.isLoggedIn()}}
path="/dashboard"
component={Dashboard}
/>
</Switch>
</Router>
</Provider>

当我从主页重定向到仪表板时,为什么会出现此错误?

最佳答案

你需要使用()来渲染Route,你需要这样改:

export const PublicRoute = ({ auth, ...props }) => {
const isAllowed = auth.isLoggedIn();
return isAllowed
? (<Redirect to="/dashboard" />)
: (<Route {...props} />)
};

私有(private)路由组件:

export const ProtectedRoute =  ({ auth, ...props }) => {
const isAllowed = auth.isLoggedIn();
return isAllowed
? (<Route {...props} />)
: (<Redirect to="/login" />)
};

关于javascript - 如果用户登录使用 React 路由器重定向到仪表板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49334250/

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