【问题标题】:Firebase - onAuthStateChanged 2 second delay. Add loading text/spinnerFirebase - onAuthStateChanged 2 秒延迟。添加加载文本/微调器
【发布时间】:2017-06-18 16:45:51
【问题描述】:

我使用 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: []
        })
      }
    });
  }

【问题讨论】:

    标签: javascript reactjs firebase firebase-authentication


    【解决方案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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-13
      • 2011-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-10
      相关资源
      最近更新 更多