我的ReactJS应用异步获取Firebase数据库,但是我想先加载数据库,然后使用数据库渲染应用。数据库加载后如何等待或重新渲染应用程序?
import React from 'react';
import * as firebase from "firebase/app";
import {config} from './dbinit'
import "firebase/database";
import Home from './panels/Home';
class App extends React.Component {
constructor(props) {
super(props);
this.setState = this.setState.bind(this);
this.state = {
activePanel: 'home',
db: null,
loading: true,
};
console.log("init");
}
componentDidMount = () => {
var self = this;
let ref = firebase
.initializeApp(config)
.database()
.ref();
ref.once("value").then(res => {
// Async request to Firebase
console.log("success", res.val())
if (res.val() != undefined){
// If response not undefined then load it to 'state'
this.setState({db: res.val(), loading: false})
}
});
console.log("after")
}
go = (e) => {
this.setState({ activePanel: e.currentTarget.dataset.to })
};
render() {
const { loading, db } = this.state;
return loading ? (
<div>loading...</div>
) : (
<View activePanel={this.state.activePanel}>
<Home id="home" fetchedUser={this.state.fetchedUser} go={this.go} db = {this.db}/>
</View>
);
}
}
export default App;
在“主页”中的render()中,我传递了“ this.db”并尝试将其放在“主页”上,但未定义。
答案 0 :(得分:1)
在用于呈现表格的行中,您不需要this.db
只是db
<Home id="home" fetchedUser={this.state.fetchedUser} go={this.go} db = {this.db}/>
应该是
<Home id="home" fetchedUser={this.state.fetchedUser} go={this.go} db = {db}/>