【问题标题】:How to access promise when using await [duplicate]使用等待时如何访问承诺 [重复]
【发布时间】:2019-08-19 22:54:48
【问题描述】:

我正在尝试访问 renderContent 函数中的 [[PromiseValue]] 以将值呈现给用户。我在控制台日志中看到数据,但不知何故我无法访问它。

class PersonalInfo extends Component {

    async fetchUser() {
        const res = await axios.get('/api/current_user')
        if(res)
            return res.data
    }


    renderContent() {
        if(this.fetchUser()) {
            const userdata = this.fetchUser()
            console.log(userdata)
            console.log(userdata.email)
        }
    }
}

render() {

        return <div>{this.renderContent()}</div>;
    }

【问题讨论】:

  • 我认为您可能遇到的问题是 renderContent 函数是同步的。所以当你打电话给this.fetchUser 时,你实际上得到了一个承诺,而不是userdata。尝试将renderContent 函数转换为async 函数,或者在组件生命周期中调用fetchUser 函数,并更新组件state,以重新渲染组件。

标签: javascript reactjs async-await


【解决方案1】:

试试这个:

async renderContent() {
    const userdata = await this.fetchUser()
    if(userdata)
    {
    console.log(userdata)
    console.log(userdata.email)

【讨论】:

  • 执行此操作时出现此错误:对象作为 React 子对象无效(找到:[object Promise])。如果您打算渲染一组子项,请改用数组。我在原始问题中添加了最终的渲染语句,是否需要在那里更改一些内容?
  • @RamSom 就像 guzmonne 之前在评论中所说的那样,你做错了——永远不要在渲染函数中使用 Ajax 获取数据。在生命周期方法(例如 componentDidMount)中触发 fetchUser 函数并将结果存储在 state 中。
  • 感谢 JJJ 的帮助,使用了成功的 componentDidMount
猜你喜欢
  • 1970-01-01
  • 2018-09-12
  • 1970-01-01
  • 2018-09-02
  • 1970-01-01
  • 2018-08-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多