【问题标题】:reactjs user authentication logicreactjs用户认证逻辑
【发布时间】:2020-03-04 20:48:53
【问题描述】:

我正在尝试为我的 react 应用实现用户身份验证功能,我的方法如下。

我创建了一个 auth 文件,例如

import { createContext, useContext } from 'react';

    export const AuthContext = createContext();
    export function useAuth() {
       return useContext(AuthContext);
    }

并在我的 App.js 中使用它,如下所示

<Switch>
      <AuthContext.Provider value={false}>
        <LoginLayout path="/" component={Login} exact />
        <LoginLayout path="/register" component={Register} />
        <HomeLayout path="/dashboard" component={Dashboard} />
        <HomeLayout path="/evc" component={EvcStations} />
      </AuthContext.Provider>
</Switch>

我创建了一个 PrivateRoute 文件来处理身份验证错误时的路由。

PrivateRoute.js

import {useAuth} from '../../services/auth'
import React from 'react';
import { Route,Redirect  } from 'react-router-dom';

    function PrivateRoute({ component: Component, ...rest }) {
        const isAuthenticated = useAuth();
        return (
            <Route {...rest} render={(props) => 
                isAuthenticated ? (
                <Component {...props} />
            ): (
                <Redirect to="/" />
              )}
            />
        );
    }
export default PrivateRoute;

我在HomeLayout 中使用了我的 PrivateRoute,如下所示。

HomeLayout.js

const HomeLayout = ({ component: Component, ...rest }) => {

    return (
        <PrivateRoute {...rest} render={matchProps => (
            <div id="">
                <div className="DefaultLayout mx-auto">
                    <div className="Header"><Header /></div>
                    <div><Component {...matchProps} /></div>
                </div>
            </div>
        )} />
    )
};
export default HomeLayout;

这就是我遇到问题的地方

如果身份验证为假,它将正确重定向到登录页面。但如果身份验证为真,我会收到一条错误消息

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

我在这里做错了什么?

【问题讨论】:

  • 您正在将渲染传递给`,并在 PrivateRoute 中使用未通过的组件
  • 是的。就是这个问题..谢谢!

标签: javascript reactjs authentication


【解决方案1】:

您不会将您的组件转发到您的PrivateRoute

const HomeLayout = ({ component: Component, ...rest }) => {

    return (
        <PrivateRoute {...rest} component={Component} render={matchProps => (
            <div id="">
                <div className="DefaultLayout mx-auto">
                    <div className="Header"><Header /></div>
                    <div><Component {...matchProps} /></div>
                </div>
            </div>
        )} />
    )
};
export default HomeLayout;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多