【发布时间】:2021-07-12 19:01:24
【问题描述】:
我已经尝试了我能找到的所有选项,但我不明白我做错了什么。 我的 axios 获取数据更新,但是当我使用条件时,它总是呈现第一个状态数据。这是我的代码。
import axios from 'axios';
import React, { Component, } from 'react'
import { Redirect } from 'react-router-dom';
import { Route } from 'react-router-dom';
class ProtectedRoute extends Component{
// _isMounted = false;
constructor(props) {
super(props);
this.state = {
Authenticated: undefined
};
}
componentWillMount(){
// this._isMounted = true;
axios.get('/api/get_me')
.then(res => {
if (this._isMounted) {
if (res.data.logged_in == true) {
this.setState({Authenticated: true});
console.log(this.state.Authenticated)
}
}
})
.catch(err =>{
this.setState({Authenticated: false});
});
}
// componentWillUnmount() {
// this._isMounted = false;
// }
render(){
const { component: Component, ...props } = this.props;
const Authenticated = this.state;
console.log(Authenticated)
if (Authenticated == true) {
return(<Route {...props} render={props => (<Component {...props} />)}/>)
}
else{
return(<Redirect to='/login' />)
}
// return (
// <Route
// {...props}
// render={props => (
// Authenticated ?
// <Component {...props} /> :
// <Redirect to='/login' />
// )}
// />
// )
}
}
export default ProtectedRoute;
每当我使用条件时,它都会带有 undefined 值。我想使用类组件而不是功能挂钩。我不明白我做错了什么以及我能做些什么来解决这个问题?我已经尝试了所有评论部分的代码,但没有解决。 这是错误。
【问题讨论】:
-
if (this._isMounted)- 你在哪里将标志设置为true?它看起来到处都被注释掉了 -
你有两个带有Authenticated的控制台日志,你怎么知道哪个是错误输出?
-
@NadiaCibrikova 它总是呈现第一个状态,正如您在控制台中看到的那样,它显示为未定义。
标签: reactjs react-redux react-router axios react-hooks