使用React-Router尝试根据state重定向用户时遇到问题

时间:2019-12-26 12:51:56

标签: javascript reactjs express react-router

我的应用程序组件将重定向使用过的(如果已登录)= true,我尝试了各种方法后使用了一个在线示例,如果有更简单的功能性反应方式,请向我展示,

如果用户已登录,我希望他们转到/ createpost,否则希望他们转到/ login路由,我想保护用户必须登录的/ createpost路由,但这是一项任务再过一段时间,尽管想法受到赞赏。

沙盒:https://codesandbox.io/s/focused-sammet-eitqr

我的应用程序组件

const App = () => {
  return (
    <Router>
      <Switch>
        <Route component={Navbar} />
        <Route exact path="/Home" component={Home} />
        <Route exact path="/posts" component={ViewPost} />
        <Route exact path="/login" component={Login} />
        <Route exact path="/register" component={Register} />

        <PrivateRoute
          path="/createpost"
          component={CreatePost}
          isAuthenticated={false}
        />
      </Switch>
    </Router>
  );
};

PrivateRoute组件

export const PrivateRoute = ({
  component: Component,
  isAuthenticated,
  ...rest
}) => (
  <Route
    {...rest}
    render={props =>
      isAuthenticated ? (
        <Component {...props} />
      ) : (
        <Redirect
          to={{
            pathname: "/login",
            state: { from: props.location }
          }}
        />
      )
    }
  />
);

1 个答案:

答案 0 :(得分:1)

我是通过以下代码完成的-

import React, { Component } from 'react';
import { BrowserRouter, Route, Switch, Redirect } from 'react-router-dom';
import { baseURL } from './components/action';
import './App.css';
import TopNavBar from './components/TopNavBar';
import SideNavBar from './components/sideNavBar';
import Footer from './components/footer';
import DashBoard from './components/dashBoard';
import Media from './components/media';
import Login from './components/Login';
import Registration from './components/Registration';
import ChangePassword from './components/changePassword';
import ForgotPassword from './components/forgotPassword';
import MyProfile from './components/myProfile';
import PageNotFound from './components/pageNotFound';

class App extends Component {
  render() {
    if (
      localStorage.getItem('token') !== undefined &&
      localStorage.getItem('token') !== '' &&
      localStorage.getItem('token') !== null
    ) {
      var token = localStorage.getItem('token');
    }

    const defaultparams = { params: { p1: '', p2: '' } };

    return (
      <BrowserRouter basename={baseURL}>
        <div>
          {token ? <TopNavBar /> : ''}
          {token ? <SideNavBar /> : ''}
          <div className="page_content">
            <Switch>
              <Route
                path="/"
                exact
                render={() => {
                  return token ? (
                    <DashBoard />
                  ) : (
                    <Login match={defaultparams} />
                  );
                }}
              />
              <Route
                path="/dashboard"
                render={() => {
                  return token ? <DashBoard /> : <Redirect to="/login" />;
                }}
              />
              <Route
                path="/media"
                render={() => {
                  return token ? <Media /> : <Redirect to="/login" />;
                }}
              />
              <Route path="/login/:p1?/:p2?" component={Login} />
              <Route
                path="/signup"
                render={() => {
                  return token ? (
                    <Redirect to="/dashboard" />
                  ) : (
                    <Registration />
                  );
                }}
              />
              <Route
                path="/forgotpassword"
                render={() => {
                  return token ? (
                    <Redirect to="/dashboard" />
                  ) : (
                    <ForgotPassword />
                  );
                }}
              />
              <Route
                path="/changepassword"
                render={() => {
                  return token ? <ChangePassword /> : <Redirect to="/login" />;
                }}
              />
              <Route
                path="/myprofile"
                render={() => {
                  return token ? <MyProfile /> : <Redirect to="/login" />;
                }}
              />
              <Route path="" component={PageNotFound} />
            </Switch>
          </div>
          <Footer />
        </div>
      </BrowserRouter>
    );
  }
}

export default App;

您需要检查令牌。如果存在,则加载组件,否则重定向用户。