【问题标题】:Can't await promise in map method无法在地图方法中等待承诺
【发布时间】:2020-05-16 10:18:57
【问题描述】:

我正在尝试呈现房间列表,然后获取房间中每个接收者的用户数据,并且由于房间中只能有 2 个用户(您 + 另一个人),因此接收者只是其他人。

async renderRooms(room, user) {
    const recipentId = room.users.filter(id => id != user.id)[0],
        recipients = await userService.getOne(recipentId);

    console.log(recipients)

    return (
        <ListGroupItem tag="a" href="#" data-unread="3" action key={room._id} onClick={this.onRoomOpened.bind(this, room._id)}>
            <img src={""} />
            <div className="details">
                <div className="recipient-name"></div>
                <div className="last-message">
                    <MessageCircle className="feather" />
                    This is an example last message...
                </div>
            </div>
        </ListGroupItem>
    );
}

render() {
    if(this.props.rooms.length < 1) return <LoadingPage />;

    return (
        <userContext.Consumer>
        {({user}) => {
            if(this.state.roomId) return <ActiveRoom id={this.state.roomId} />;
            else
                return (
                    <ListGroup className="recipients">
                        {this.props.rooms.map(room => this.renderRooms(room, user))}
                    </ListGroup>
                );
        }}
        </userContext.Consumer>
    );
}

这样我从用户数组中过滤掉我自己的用户ID,然后我取出剩余的ID并使用promise来获取它的用户数据。但这里的问题是,每当我调用await 时,它都会抛出错误:

react-dom.development.js:14748 未捕获错误:对象无效 作为 React 孩子(发现:[object Promise])。如果你打算渲染一个 孩子的集合,请改用数组。

如果我尝试使用.then(),它实际上似乎根本没有被调用,例如,如果我将console.log 放在那里,它什么也不会打印出来。 知道如何完成我的任务吗?

【问题讨论】:

标签: javascript reactjs async-await react-context


【解决方案1】:

您不能在render 方法中调用异步函数。

异步函数返回一个 Promise 对象,所以这个

{this.props.rooms.map(room => this.renderRooms(room, user))}

将返回一个 Promise 对象数组,并且不能渲染和对象。

您需要在componentDidMount 中调用您的异步函数,并在加载数据时渲染它。

查看此answer 了解如何操作的示例。

【讨论】:

  • 感谢您的解释!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-16
  • 2017-12-08
  • 1970-01-01
  • 1970-01-01
  • 2019-04-29
  • 2020-10-31
  • 1970-01-01
相关资源
最近更新 更多