react之異步請求數據,render先行渲染報錯,未拿到數據


import React from 'react'
import {connect} from 'react-redux'
import { Redirect} from 'react-router-dom'
import axios from 'axios'
import {login} from './Auth.redux.js'

//兩個reducers 每個reducers都有一個state
@connect(
    (state)=>state.auth,
    {login}
)
class Auth extends React.Component{
  constructor(props){
    super(props)
    this.state={
      data:{},
      success:false   //解決方法設置一個開關,當數據請求成功,置為true
    }
  }
    componentDidMount(){
      axios.get('/data')
        .then(res=>{
          if(res.status===200){
            this.setState({data:res.data,success:true})
            console.log(this.state.data[0].user)
            debugger
          }
        })
    }
    render(){
        return (
            <div>
                <h2>我的名字是{this.state.success?this.state.data[0].user:''}</h2>
                {this.props.isAuth?<Redirect to='/dashboard'></Redirect>:null}
                <h2>你沒有權限需要登錄</h2>
                <button onClick={this.props.login}>登錄</button>
            </div>
        )
    }
}

export default Auth


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM