首页 > 解决方案 > 如何在 React 中获取更新的构造函数数据

问题描述

我正在创建一条私有路由,这是 Auth js 文件。

Auth.js

import axios from "axios";

class Auth{
    constructor(){
        this.Authenticated = false;
    }

    CheckAuth(cb){
        axios.get('/api/get_me')
          .then(res => {
              if (res.data.logged_in == true) {
                this.Authenticated = true;
              }
          })
          .catch(err =>{
            this.Authenticated = false;
          });
        cb();
    }

    isAuthenticated(){
        return this.Authenticated;
    }
}

export default new Auth();

我从我的私有路由组件调用它,但总是得到错误就像它总是得到第一个this.Authenticated值而不是更新所以我该怎么做,我的问题是什么

私有.jsx

import React, { Component, useEffect  } from 'react'
import { Redirect, Route } from 'react-router-dom';
import auth from './Auth';

export const  ProtectedRoute = ({component: Component, ...rest}) => {
  return(
    <Route 
      {...rest}
        render={props =>{
          console.log(auth.isAuthenticated());
          if (auth.isAuthenticated()) {
            return <Component></Component>
          }
          else{
            return(
            <Redirect to={{pathname: '/login', state: { from: props.location}}}></Redirect>)
          }
          
        }}
    />
  )
}

这是api调用数据。 在此处输入图像描述

谢谢你。

标签: javascriptreactjsreact-reduxaxiosreact-hooks

解决方案


最好的方法是创建一个 HOC(高阶组件)。

我刚刚在这里写了一个例子

import React, { useEffect, useState } from "react";

const withAuthentication = (Component) => (props) => {
  const [auth, setAuth] = useState(false);
  const [isLoading, setLoading] = useState(true);
  useEffect(() => {
    const checkAuthentication = () => {
      setTimeout(() => {
        setAuth(true);
        setLoading(false);
      }, 2000);
    };
    checkAuthentication();
  }, []);

  if (isLoading) {
    return <div>Loading...</div>;
  }

  return (
    <div>
      {auth ? <Component {...props} /> : <div>No permission component</div>}
    </div>
  );
};

const Div = (props) => {
  console.log(props);
  return <div>Test</div>;
};

export default function App() {
  const Comp = withAuthentication(Div);

  return (
    <div>
      <Comp match={{ params: ["foo"] }} />
    </div>
  );
}

推荐阅读