在渲染类组件之前反应获取数据

时间:2021-04-18 10:20:53

标签: reactjs react-redux react-router axios react-hooks

我已经尝试了所有我能找到的选项,但我不明白我做错了什么。 我的 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 值。我想使用类组件而不是功能挂钩。我不明白我做错了什么,我能做些什么来解决这个问题?我已经尝试了所有评论部分的代码,但没有解决。 这是错误。 enter image description here

4 个答案:

答案 0 :(得分:0)

您缺少 name 属性。因为它是一个对象,所以你必须这样称呼它。否则它将返回 undefined。

const Authenticated = this.state.Authenticated

答案 1 :(得分:0)

这不是正确的解构

const Authenticated = this.state;

正确一个

const { Authenticated } = this.state;

或 像这样赋值

const Authenticated = this.state.Authenticated ;

查看此内容以更好地了解 Destructuring

答案 2 :(得分:0)

您必须取消注释 // this._isMounted = true;componentWillMount 和第 7 行的 _isMounted = false

您的 Authenticated 状态为 undefined,因为您的 API 可能正在解析,但 this._isMounted 未定义,因为您已将它们注释掉。

如其他答案所述,您还需要通过适当的解构来正确获得您的 Authenticated 状态。 const { 已认证} = this.state;

因此,关于您在等待 API 响应时不想重定向的响应。您可能想要添加加载状态。这样,您的应用会在等待 API 解析而不是重定向时显示一些内容。

constructor(props) {
  super(props);
  this.state = {
    Authenticated: undefined
    isLoading: true,
  };
}

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});
     })
     .finally(() => {
       this.setState({ isLoading: false });
     });
}

render(){
    const { component: Component, ...props } = this.props;
    const {Authenticated, isLoading} = this.state;
    console.log(Authenticated)

    if(isLoading) {
      return <div>Loading...</div>
    }
    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' />
    //     )} 
    //   />
    // )
}
      

答案 3 :(得分:0)

你有没有检查过在finally块中设置状态后你的状态是什么样的?您确定没有覆盖其他值吗?

尝试使用扩展运算符保留状态中的每个值: React - Overwrite part of the state.object's values whilst preserving the old ones.

此外,我认为真的不再推荐 componentWillMount,这里是有关更安全版本的官方指南,可以将其替换为:

https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html