将 setState 反应为从 http 响应接收到的值

React setState to value received from http response

首先,请原谅我的英语,我不是母语人士。 我会尽力解释。

我正在尝试将我的组件的状态设置为从 componentDidMount() 上运行的 http 请求收到的值。在 setState 之后,我将 props 传递给我的子组件并期望它们重新渲染。

//App.js
import getAuthStateFromServer from './getAuthStateFromServer'

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      AuthState
    }
    this.getAuthState.bind(this)
  }

  componentDidMount() {
    this.getAuthState()
  }

  getAuthState() {
     getAuthStateFromServer().then(AuthState => 
       this.setState({ AuthState })
     ) 
  }

   render() {
     return <h1>{this.state.AuthState.userData.userName}</h1>
   }
}


//getAuthStateFromServer.js

import axios from 'axios'
import { getAuth } from './AuthStorage' 

const getAuthStateFromServer = () => new Promise((resolve, reject) => {
   // Create AuthState object
   const AuthState = {
     userData: {},
     isLoggedIn: false,
   }
   // 1. get token
   const { token } = getAuth()
   // 2. if have token
   if(token) {
     // authenticate!
     // send get request with token in header
     axios.get('http://localhost:3500/validate', {
       headers: { 'Authorization': `Bearer ${token}` }
     }).then((res) => {
        AuthState.userData = res.data
        AuthState.isLoggedIn = true
        resolve(AuthState)
     }).catch(e => reject(e))
   }
   resolve(AuthState)
  })

 export default getAuthStateFromServer

因此,当我在控制台记录它时,它为我提供了 AuthState 对象,但它没有重新呈现我的组件。

但是如果我把我的 getAuthFromServerFunction 里面的东西像这样放在我的 componentDidMount 中..

componentDidMount() {
  this.getAuthState()
 }

 getAuthState() {
   const AuthState = {
     userData: {},
     isLoggedIn: false,
   }
   // 1. get token
   const { token } = getAuth()
   axios.get('http://localhost:3500/validate', {
      headers: { 'Authorization': `Bearer ${token}` },
   }).then((res) => {
     AuthState.userData = res.data
     AuthState.isLoggedIn = true
     this.setState({ AuthState })
   })
 }

有效..我的组件重新渲染

我完全无法理解这个问题.. 任何帮助将不胜感激,谢谢

我觉得你的getAuthStateFromServer功能不好

我能感觉到它总是被解析为相同的值;)

const getAuthStateFromServer = () => new Promise((resolve, reject) => {
   // Create AuthState object
   const AuthState = {
     userData: {},
     isLoggedIn: false,
   }
   // 1. get token
   const { token } = getAuth()
   // 2. if have token
   if(token) {
     // authenticate!
     // send get request with token in header
     axios.get('http://localhost:3500/validate', {
       headers: { 'Authorization': `Bearer ${token}` }
     }).then((res) => {
        AuthState.userData = res.data
        AuthState.isLoggedIn = true
        resolve(AuthState) // <-- When this line will be called, the promise will always be resolved by the line below.
     }).catch(e => reject(e))
   }
   resolve(AuthState) // <-- This line will always be called before the one with the value above. 
  })

删除最后一行resolve(AuthState),这违背了你的诺言!看看我在上面代码中的评论 ;)