如何重定向到 /user/dashboard

IT技术 reactjs react-router
2021-05-21 01:06:26

我必须/user/dashboard在登录后重定向到该页面,但是每次我关闭该选项卡并再次打开它时,它都会打开默认主页,即/.

import React from 'react';
import {isAuthenticated} from '../helpers/auth' 
import {Route, Redirect } from 'react-router-dom';
const UserRoute = ({component: Component, ...rest}) => {
    return(
        <Route 
            {...rest}
            render={(props)=>
                isAuthenticated() && isAuthenticated().role === 0 ? (
                    <Component {...props} />
                ):(
                    <Redirect to="/signin" />
                )
            }
        />
    );
}

导出默认用户路由;

1个回答

这是路由设置的一般示例,它会检查“公共”、“私有”和索引路径:

export default function Routes() {

  function fromIndex() {
    if (isAuthenticated) { // use your authentication mechanism
        return '/user/dashboard'
    }
    return '/login'
  }

  return (
    <Router history={history}> {/* history not required when using BrowserRouter */}
      <Switch>
        <Redirect exact from="/" to={fromIndex()} />

        {/* publicPaths is an array of paths: [{...} */}
        {publicPaths.map(item => (
          <PublicRoute exact={item.exact} key={item.path} path={item.path}>
            <item.component />
          </PublicRoute>
        ))}

        {privatePaths.map(item => (
          <PrivateRoute exact={item.exact} key={item.path} path={item.path}>
            <item.component />
          </PrivateRoute>
        ))}

        <NotFoundPage />
      </Switch>
    </Router>
  )
}

这里PrivateRoute是一个组件,它呈现childrenif 身份验证否则重定向回 '/login'。

并且PublicRoute是一个组件,它呈现children如果未通过身份验证,否则重定向回“/”。