我很反应并尝试使用react和firebase构建一个简单的应用程序。
我有父类Homepage.js,我把我的其他组件HomePageRecipe.js放在这里:
<HomePageRecipe changeToRecipes={this.showRecipes.bind(this)} />
在我的HomePageRecipe中,我有一个名为componentDidMount
的函数,我获取了firebase数据。这是功能:
componentDidMount(){
let recipePath = "/recipe";
firebase.database().ref(recipePath).on('child_added', (snapshot) => {
this.setState({title: snapshot.val().title});
this.setState({recipeKey: snapshot.key});
this.setState({previousKeys: [...this.state.recipeKeys, this.state.recipeKey]});
this.setState({previousList: [...this.state.titleForRecipeList, this.state.title]});
this.setState({titleForRecipeList: this.state.previousList});
this.setState({recipeKeys: this.state.previousKeys});
});
}
我添加第三个组件时出现问题。在这里我选择不在HomePageRecipe.js中显示HomePage.js。当我回到带有HomePageRecipe.js组件的HomePage.js组件时,函数componentDidMount()
内部没有再次调用,我该如何调用它?还是有一种更新功能?提前谢谢
答案 0 :(得分:0)
试试这个:
componentDidMount() {
let recipePath = "/recipe";
var self = this;
firebase.database().ref(recipePath).once('value').then(function (snapshot) {
snapshot.forEach(x => {
self.setState({title: x.val().title});
self.setState({recipeKey: x.key});
self.setState({previousKeys: [...self.state.recipeKeys, self.state.recipeKey]});
self.setState({previousList: [...self.state.titleForRecipeList, self.state.title]});
self.setState({titleForRecipeList: self.state.previousList});
self.setState({recipeKeys: self.state.previousKeys});
});
});
}