我使用 React + firebase 创建了一个待办事项列表。用户注册并登录后,他们可以访问他们的待办事项列表,但登录后,如果您刷新页面,onAuthStateChange 检查他们是否已登录需要 2/3 秒,这意味着他们会看到登录屏幕几秒钟后就会看到他们的待办事项列表。
我希望有一个简单的方法来添加加载文本/旋转器等待刷新的 2/3 秒?
JS
class App extends React.Component {
constructor() {
super();
this.state = {
toDo: [],
loggedIn: false
}
this.addToDo = this.addToDo.bind(this);
this.deleteToDo = this.deleteToDo.bind(this);
}
componentDidMount() {
firebase.auth().onAuthStateChanged((user) => {
if(user) {
const dbRef = firebase.database().ref(`users/${user.uid}`);
dbRef.on("value", (res) => {
const toDoArr = [];
let toDoObj = res.val();
for(let objKey in toDoObj) {
toDoObj[objKey].key = objKey;
toDoArr.push(toDoObj[objKey]);
}
this.setState({
toDo: toDoArr,
loggedIn: true
});
});
} else {
this.setState({
loggedIn: false,
toDo: []
})
}
});
}
最佳答案
您可以将 loading
属性作为状态的一部分。像这样的事情
constructor() {
// .....
this.state = {
loading: true,
toDo: [],
loggedIn: false
}
}
从状态加载可以用这种方式渲染
render() {
if (this.state.loading){
return <Loading>My sweet spinner</Loading>;
}
// .... rest of the render
}
class App extends React.Component {
constructor(props){
super(props);
this.state = {
loading: true,
name: ''
};
}
componentDidMount() {
setTimeout(function() {
this.setState({
loading: false,
name: 'Stackoverflow'
});
}.bind(this), 2000);
}
render() {
if(this.state.loading){
return <div> Loading ... </div>;
}
return <div>This is {this.state.name}</div>;
}
}
ReactDOM.render(<App />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="app"></div>
关于javascript - Firebase - onAuthStateChanged 2 秒延迟。添加加载文本/微调器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44617280/