我正在使用Firebase作为后端,并且正在为Restaurant实体创建详细视图。一家餐厅有一系列的菜品ID,因此我想在查看餐厅时列出这些菜品。
在菜品列表组件中,我得到了菜品ID数组作为道具。然后,我浏览每个菜肴ID,并从Firebase获取菜肴数据。我在 componentWillReceiveProps 中执行此操作,以获取父组件中的最新状态更新。
这是菜品清单组件:
array(6) {
[0] =>
array(4) {
'item' =>
string(4) "pear"
'quality' =>
int(1)
'store' =>
string(4) "bobs"
'price' =>
int(3)
}
[1] =>
array(4) {
'item' =>
string(6) "banana"
'quality' =>
int(2)
'store' =>
string(5) "freds"
'price' =>
int(1)
}
[2] =>
array(4) {
'item' =>
string(7) "coconut"
'quality' =>
int(2)
'store' =>
string(4) "sams"
'price' =>
int(6)
}
[3] =>
array(4) {
'item' =>
string(4) "kiwi"
'quality' =>
int(2)
'store' =>
string(4) "sams"
'price' =>
int(4)
}
[4] =>
array(4) {
'item' =>
string(5) "apple"
'quality' =>
int(3)
'store' =>
string(5) "freds"
'price' =>
int(2)
}
[5] =>
array(4) {
'item' =>
string(4) "lime"
'quality' =>
int(3)
'store' =>
string(4) "sams"
'price' =>
int(5)
}
}
这是父组件:
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>
)
}
}
任何暗示为什么会发生这种情况都非常感谢!