8wDlpd.png
8wDFp9.png
8wDEOx.png
8wDMfH.png
8wDKte.png

如何使用 react-router-dom 创建受保护的路线?

Harley 1月前

50 0

如何使用 react-router-dom 创建受保护的路由并将响应存储在 localStorage 中,以便用户下次尝试打开时可以再次查看其详细信息。登录后,他们应该

如何创建受保护的路由 react-router-dom 并将响应存储在 localStorage 中,以便用户下次尝试打开时可以再次查看其详细信息。登录后,他们应该重定向到仪表板页面。

所有功能均添加在 ContextApi.代码sandbox 链接中: Code

我尝试过,但没能实现

路线页面

import React, { useContext } from "react";
import { globalC } from "./context";
import { Route, Switch, BrowserRouter } from "react-router-dom";
import About from "./About";
import Dashboard from "./Dashboard";
import Login from "./Login";
import PageNotFound from "./PageNotFound";

function Routes() {
  const { authLogin } = useContext(globalC);
  console.log("authLogin", authLogin);

  return (
    <BrowserRouter>
      <Switch>
        {authLogin ? (
          <>
            <Route path="/dashboard" component={Dashboard} exact />
            <Route exact path="/About" component={About} />
          </>
        ) : (
          <Route path="/" component={Login} exact />
        )}

        <Route component={PageNotFound} />
      </Switch>
    </BrowserRouter>
  );
}
export default Routes;

上下文页面

import React, { Component, createContext } from "react";
import axios from "axios";

export const globalC = createContext();

export class Gprov extends Component {
  state = {
    authLogin: null,
    authLoginerror: null
  };
  componentDidMount() {
    var localData = JSON.parse(localStorage.getItem("loginDetail"));
    if (localData) {
      this.setState({
        authLogin: localData
      });
    }
  }

  loginData = async () => {
    let payload = {
      token: "ctz43XoULrgv_0p1pvq7tA",
      data: {
        name: "nameFirst",
        email: "internetEmail",
        phone: "phoneHome",
        _repeat: 300
      }
    };
    await axios
      .post(`https://app.fakejson.com/q`, payload)
      .then((res) => {
        if (res.status === 200) {
          this.setState({
            authLogin: res.data
          });
          localStorage.setItem("loginDetail", JSON.stringify(res.data));
        }
      })
      .catch((err) =>
        this.setState({
          authLoginerror: err
        })
      );
  };
  render() {
    // console.log(localStorage.getItem("loginDetail"));
    return (
      <globalC.Provider
        value={{
          ...this.state,
          loginData: this.loginData
        }}
      >
        {this.props.children}
      </globalC.Provider>
    );
  }
}
帖子版权声明 1、本帖标题:如何使用 react-router-dom 创建受保护的路线?
    本站网址:http://xjnalaquan.com/
2、本网站的资源部分来源于网络,如有侵权,请联系站长进行删除处理。
3、会员发帖仅代表会员个人观点,并不代表本站赞同其观点和对其真实性负责。
4、本站一律禁止以任何方式发布或转载任何违法的相关信息,访客发现请向站长举报
5、站长邮箱:yeweds@126.com 除非注明,本帖由Harley在本站《reactjs》版块原创发布, 转载请注明出处!
最新回复 (0)
  • import { v4 as uuidv4 } from "uuid";
    
    const routes = [
        {
            id: uuidv4(),
            isProtected: false,
            exact: true,
            path: "/home",
            component: param => <Overview {...param} />,
        },
        {
            id: uuidv4(),
            isProtected: true,
            exact: true,
            path: "/protected",
            component: param => <Overview {...param} />,
            allowed: [...advanceProducts], // subscription
        },
        {
            // if you conditional based rendering for same path
            id: uuidv4(),
            isProtected: true,
            exact: true,
            path: "/",
            component: null,
            conditionalComponent: true,
            allowed: {
                [subscription1]: param => <Overview {...param} />,
                [subscription2]: param => <Customers {...param} />,
            },
        },
    ]
    
    // Navigation Component
    import React, { useEffect, useState } from "react";
    import { useSelector } from "react-redux";
    import { Switch, Route, useLocation } from "react-router-dom";
    
    // ...component logic
    <Switch>
        {routes.map(params => {
            return (
                <ProtectedRoutes
                    exact
                    routeParams={params}
                    key={params.path}
                    path={params.path}
                />
            );
        })}
        <Route
            render={() => {
                props.setHideNav(true);
                setHideHeader(true);
                return <ErrorPage type={404} />;
            }}
        />
    </Switch>
    
    // ProtectedRoute component
    import React from "react";
    import { Route } from "react-router-dom";
    import { useSelector } from "react-redux";
    
    const ProtectedRoutes = props => {
        const { routeParams } = props;
        const currentSubscription = 'xyz'; // your current subscription;
        if (routeParams.conditionalComponent) {
            return (
                <Route
                    key={routeParams.path}
                    path={routeParams.path}
                    render={routeParams.allowed[currentSubscription]}
                />
            );
        }
        if (routeParams.isProtected && routeParams.allowed.includes(currentSubscription)) {
            return (
                <Route key={routeParams.path} path={routeParams.path} render={routeParams?.component} />
            );
        }
        if (!routeParams.isProtected) {
            return (
                <Route key={routeParams.path} path={routeParams.path} render={routeParams?.component} />
            );
        }
        return null;
    };
    
    export default ProtectedRoutes;

    想要添加亮点永远不要忘记将路径作为 prop 提供给 ProtectedRoute,否则它将不起作用。

返回
作者最近主题: