[英]How to console.log data retrieved from asynchronous api call?
I'm making an API call to a server and sending to a React component.我正在对服务器进行 API 调用并发送到 React 组件。 I'm trying to work out if the data has been loaded successfully and how it looks once it is loaded.
我正在尝试确定数据是否已成功加载以及加载后的外观。
However, when I console.log
the data I obviously only receive a promise
object.但是,当我
console.log
记录数据时,我显然只收到promise
object。 Does anyone know how to ensure the console.log
only fires once the API call is complete?有谁知道如何确保
console.log
仅在 API 调用完成后触发? I've tried to use async
and await
although I've struggled to get it working.我尝试使用
async
和await
虽然我一直在努力让它工作。
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)
If this.players
returns a promise, you can use .then()
to do something with its response.如果
this.players
返回 promise,您可以使用 .then .then()
对其响应进行处理。
this.players.then(res => console.log(res)).catch(err => console.log(err))
Here is your code with async
and await
and a little clean up:这是您的代码,带有
async
和await
并进行了一些清理:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.