【问题标题】:Protected Route and React Context受保护的路由和反应上下文
【发布时间】:2020-06-01 20:46:17
【问题描述】:

我有一个上下文 (AuthContext),它可以让我知道用户是否经过身份验证。我还创建了一个受保护的路由,如果用户通过身份验证,我可以登录到 DashBoard,否则重定向到登录。但是,我在将这两者连接在一起时遇到了问题。

ProtectedRoute.js

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

const ProtectedRoute = ({ component: Component, ...rest }) => {
  return (
    <AuthContext.Consumer>
      {(context) => {
        const { isAuthenticated } = this.context;

        return (
          <Route
            {...rest}
            render={(props) => {
              const { isAuthenticated } = this.context; //getting an error here
              if (isAuthenticated) {
                return <Component {...props} />;
              } else {
                return (
                  <Redirect
                    to={{
                      pathname: '/',
                      state: {
                        from: props.location,
                      },
                    }}
                  />
                );
              }
            }}
          />
        );
      }}
    </AuthContext.Consumer>
  );
};

export default ProtectedRoute;

AuthContext.js

import React, { Component, createContext } from 'react';

export const AuthContext = createContext();

class AuthContextProvider extends Component {
  state = {
    isAuthenticated: false,
  };
  toggleAuth = () => {
    this.setState({ isAuthenticated: !this.state.isAuthenticated });
  };

  render() {
    return (
      <AuthContext.Provider
        value={{ ...this.state, toggleAuth: this.toggleAuth }}>
        {this.props.children}
      </AuthContext.Provider>
    );
  }
}

export default AuthContextProvider;

编辑的代码(得到一个错误,说渲染不是一个函数)

import React from 'react'
import { Route, Redirect } from 'react-router-dom'
import { AuthContext } from './AuthContext'



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

    return (
        <AuthContext.Consumer>
            {({context}) => (   
                <Route
                    {...rest}
                    render={(props) => {
                    const {isAuthenticated} = context;
                        if(isAuthenticated) {
                            return <Component {...props} />;
                        } else {
                            return (
                                <Redirect
                                to={{
                                    pathname: "/",
                                    state: {
                                        from: props.location
                                    }
                                }}
                                />
                            );
                         } 
                    }}
                />
            )};
        </AuthContext.Consumer>
    )
}

export default ProtectedRoute

【问题讨论】:

    标签: javascript reactjs routes react-router react-context


    【解决方案1】:

    提供给上下文消费者函数的参数是相应提供者中的value prop。

      return (
        <AuthContext.Consumer>
          {(context) => (
            <Route
              {...rest}
              render={(props) => {
                const { isAuthenticated } = context; // no `this`
                // ...
              }}
            />
          )}
        </AuthContext.Consumer>
      );
    

    我注意到您的原始代码中有一些语法错误:

    • 如果您使用return,则需要将消费者函数的主体括在大括号中。
    • 由于消费者函数是消费者元素的子元素,因此您需要提供一个结束标记。

    【讨论】:

    • 我仍然收到一个错误,说渲染不是一个函数。在原始帖子中发布了我编辑的代码。
    • 您能否将您的确切错误和任何其他上下文添加到您的问题中?
    猜你喜欢
    • 2020-10-04
    • 2021-09-28
    • 2022-11-16
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    • 2021-03-05
    • 2021-07-19
    • 2020-10-26
    相关资源
    最近更新 更多