2017-06-18 21 views
0

React + firebaseを使用してリストを作成しました。ユーザーがサインアップしてログインした後、リストにアクセスできますが、ページを更新するとログインしたときにonAuthStateChangeチェックがログインしているかどうかを確認するのに2/3秒かかります。彼らのリストを見る前に数秒。Firebase - onAuthStateChanged 2秒の遅延。読み込みテキストを追加/スピナー

読み込み中のテキスト/スピナーを2/3秒間追加する簡単な方法がありましたが、リフレッシュするのを待っていましたか?あなたは状態の一部としてloading属性を持つことができ

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

。状態からこの

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>

をレンダリングで使用することができます