javascript - 如何在 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>)
}
}}
/>
)
}
谢谢你。
解决方案
最好的方法是创建一个 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>
);
}
推荐阅读
- python - 没有传入时如何避免“1”
- c# - ac#软件使用adb控制安卓设备
- php - mysql和PHP中两个日期的区别
- python - 在 Ubuntu 18.04 中导入 tensorflow-gpu 时遇到问题
- json - 在 json 模式中使用“$ref”时出现 MalformedURLException
- git-config - 无法更新 git config:无法锁定文件 [home]/snap/gitkraken/137/.gitconfig.lock' 以进行写入:
- mysql - 更改 laravel 数据库表名
- r - 获取匹配条件的第一个值(循环太慢)
- python - python中的最大似然估计
- karate - 无法使用类路径或相对路径读取 json 有效负载数据