如何console.log从异步api调用中检索到的数据?

时间:2019-11-03 17:06:21

标签: javascript reactjs api asynchronous async-await

我正在对服务器进行API调用并将其发送到React组件。我正在尝试确定数据是否已成功加载,以及加载后的外观。

但是,当我console.log数据时,我显然只收到一个promise对象。有谁知道如何确保console.log仅在API调用完成后才触发?我一直尝试使用asyncawait,尽管我一直在努力使其正常工作。

import React from 'react'
import { Field, reduxForm } from 'redux-form'
import { connect } from 'react-redux'

// actions
import { getPlayers, deletePlayer } from '../actions'
// components
import RenderPlayer from './RenderPlayer'

class DeletePlayer extends React.Component {
  constructor (props) {
    super(props)
    this.players = null
    this.renderPlayerList = null
  }

  componentDidMount () {
    this.players = this.props.getPlayers()

    this.renderPlayerList = () => {
      //map over each player entry in database and send all details as props to rednderPlayer
      this.players = this.players.map((player) => { return <RenderPlayer {...player} /> })

      return this.players
    }

    console.log(this.players)

    return this.players
  }

  render () {
    return (
      <div>
        {this.players}
      </div>
    )
  }
}

export default connect(null, { getPlayers, deletePlayer })(DeletePlayer)

2 个答案:

答案 0 :(得分:2)

如果# Rewards for levels 0 to 10. rewards = [0, 150, 225, 330, 500, 1000, 1500, 2250, 3400, 5000, 15000] # Running totals. lists = [] total = 0 while True: # Get reward level from the user. If not a valid reward level, stop. level = input('-> ') try: level_num = int(level) except ValueError: break if level_num not in range(len(rewards)): break # Add the reward to the lists and the total. reward = rewards[level_num] lists.append(reward) total += reward # Final output. print(lists) print(total) 返回了一个承诺,则可以使用this.players对其响应进行某些操作。

.then()

答案 1 :(得分:1)

这是您的带有asyncawait的代码,并进行了一些清理:

import React from 'react'
import { connect } from 'react-redux'

import { getPlayers, deletePlayer } from '../actions'

import RenderPlayer from './RenderPlayer'

class DeletePlayer extends React.Component {
  state = {
    players: [],
  }

  async componentDidMount () {
    const { getPlayers } = this.props

    try {
      const players = await getPlayers()

      console.log(players)

      this.setState({ players })
    }
    catch (error) {
      console.error(error)
    }
  }

  render () {
    const { players } = this.state

    return (
      <div>
        {players.map(player => <RenderPlayer {...player} />)}
      </div>
    )
  }
}

export default connect(null, { getPlayers, deletePlayer })(DeletePlayer)