2017-06-18 64 views
0

我已經使用React + firebase創建了一個待辦事項列表。用戶註冊並登錄後,他們可以訪問他們的待辦事項清單,但是如果刷新頁面時登錄,onAuthStateChange檢查以查看他們是否已登錄需要2/3秒,這意味着他們會看到登錄屏幕幾秒鐘後纔看到他們的名單。Firebase - onAuthStateChanged延遲2秒。添加加載文本/微調

我希望有一個簡單的方法來加載文本/微調器爲他們等待刷新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: [] 
     }) 
     } 
    }); 
    } 

回答

1

你可以有一個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>