【问题标题】:State Updates After Second Load of componentWillReceiveProps and will not map在第二次加载 componentWillReceiveProps 后状态更新并且不会映射
【发布时间】:2019-07-03 20:31:18
【问题描述】:

我正在将属性从父级传递给子级,并希望映射结果数组。

当我尝试控制台记录结果时,属性仅在第二次调用该函数后才到达。第一次返回“[]”。即使收到状态“用户”数组,映射它也无济于事。

state={
    users: null
}

componentWillReceiveProps(){
    var userInLobby = this.props.users && this.props.users.map(userdata=>{
        if(userdata.status === "online"){
            var user = 
firebase.firestore().collection("users").doc(userdata.id).get().then(user=>{
                return {
                    username: user.data().username,
                };
            })
            return user

        }else{
            return null;
        }
        })
        var userInLobbyDisplay = []
        userInLobby && Promise.all(userInLobby).then(values => 
values.map(user=>{
            return userInLobbyDisplay.push(user)
        }))
        this.setState({
            users: userInLobbyDisplay
        })


}
render(){
console.log(this.state.users)
return(
<div className="lobby">
{
        this.state.users && this.state.users.map(user=>{
            return user.username
    })
}
</div>
)

第一次接收 props 时,如何将用户数组从 state 映射到 DOM?

【问题讨论】:

    标签: reactjs firebase


    【解决方案1】:

    您正在使用即将被弃用的 API,您应该遵循文档指南并切换到较新的 API,特别是新的 getDerivedStateFromProps 您可以阅读更多信息 here

    static getDerivedStateFromProps(props, state) {
        // Your code here
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-30
      • 1970-01-01
      • 2016-04-22
      • 2020-11-08
      • 2021-10-28
      • 1970-01-01
      相关资源
      最近更新 更多