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

时间:2018-07-04 13:09:39

标签: javascript reactjs setstate react-lifecycle

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

我试图将组件的状态设置为从在componentDidMount()上运行的http请求接收的值。在setState之后,我正在将道具传递给我的子组件,并希望它们重新呈现。

//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 })
   })
 }

它有效..并且我的组件重新渲染

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

1 个答案:

答案 0 :(得分:0)

我认为您的document功能不好。

我可以感觉到它将始终解析为相同的值;)

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. }) ,这违反了您的承诺!在上面的代码中查看我的评论;)