首页 > 解决方案 > firebase + react,setState 似乎不会触发重新渲染

问题描述

我正在使用 firebase 作为后端,并且正在为餐厅实体制作详细视图。一家餐厅有一系列菜肴 ID,基于此,我想在查看餐厅时列出菜肴。

在菜品列表组件中,我得到菜品 ID 数组作为道具。然后,我检查每个菜品 ID,并从 firebase 获取菜品数据。我在componentWillReceiveProps中这样做是为了在父组件中获取最新的状态更新。

这是菜品清单组件:

class DishList extends Component {
    constructor(props){
        super(props)
        this.state = {
            Dishes: []
        }
    }

    componentWillReceiveProps(props) {
        const tempDishes = []
        props.dishes.map(dish => {
            firebaseDishes.child(dish).on("value", snap => {
                if (tempDishes.findIndex(x => x.id === snap.key) == -1) {
                    // push only if id doesn't exist
                    tempDishes.push({
                        id: snap.key,
                        name: snap.val().name,
                        price: snap.val().price
                    })
                    this.setState({
                        Dishes: tempDishes
                    })
                } else {
                    const updatedTempDishes = tempDishes.slice()
                    updatedTempDishes[updatedTempDishes.findIndex(x => x.id === snap.key)] = {
                        id: snap.key,
                        name: snap.val().name,
                        price: snap.val().price
                    }
                    this.setState({
                        Dishes: updatedTempDishes
                    })
                }
            })
        })
    }

    render(){
        return(
            <div className="dishes">
            {
                this.state.Dishes.map(dish => {
                    return(
                        <DishListItem key={dish.id} 
                                    DishId={dish.id}
                                    DishName={dish.name} 
                                    DishPrice={dish.price}/>
                    )
                })
            }
            </div>
        )
    }
}

这是父组件:

class Place extends Component {
    constructor(props){
        super(props)
        this.state = {
            Place: {
                name: '',
                address: '',
                dishes: []
            }
        }
    }

    componentDidMount(){
        firebasePlaces.child(this.props.placeId).on("value", snap => {
            this.setState({
                Place: snap.val()
            })
        })
    }

    render(){
        return(
            <div>
                <h1 className="name"> {this.state.Place.name} </h1>
                <h3 className="address"> {this.state.Place.address} </h3>
                <DishList dishes={this.state.Place.dishes} />
            </div>
        )
    }
}

什么有效:

什么不起作用:

我检查过的内容:

像这样:

this.setState({
    Dishes: []
}, () => {
    this.setState({
        Dishes: updatedTempDishes
    })
})

非常感谢任何有关为什么会发生这种情况的提示!

标签: javascriptreactjsfirebasefirebase-realtime-database

解决方案


推荐阅读