javascript - 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>
)
}
}
什么有效:
- 菜品列表在页面加载时正确填充 (1)
什么不起作用:
- 如果我在 firebase 上更新一道菜,它不会更新 UI 上的列表 (2)
我检查过的内容:
- 回调函数正确用于更新,即如果我在 firebase 中更改菜条目,我会在 snap.val() 下获得该数据
- 状态改变。如果我在 setState 调用之前和之后在 setState 完成回调中检查状态,我会看到两种状态之间的区别
- 如果我先清空状态,然后在完成回调中使用新数据再次设置状态,它会更新 UI
像这样:
this.setState({
Dishes: []
}, () => {
this.setState({
Dishes: updatedTempDishes
})
})
非常感谢任何有关为什么会发生这种情况的提示!