React Native-当所有组件都已呈现在其中时,如何隐藏初始屏幕?

时间:2018-10-28 09:58:43

标签: firebase react-native

我有一个从Firebase提取数据的函数,提取完成并设置状态后会调用SplashScreen.hide()。问题是,当调用SplashScreen.hide()时,组件在出现之前仍在加载1-2秒,是否有更好的方法来确保已经渲染了组件?呈现的项目取决于状态cardComponents,状态react-native-splash-screen设置后将呈现卡片。

P.S。我正在使用fetchCards = () => { let cardRef = firebase.firestore().collection('tblcard') let itemRef = firebase.firestore().collection('tblitem') let cards = [] let items = [] let cardComponents = [] let today = new Date() today.setHours(0, 0, 0, 0) cardRef.where('date', '=', today).get().then(function(cardSnapshot) { cardSnapshot.forEach(function(doc) { cards[doc.id] = doc.data() }) itemRef.get().then(function(itemSnapshot) { itemSnapshot.forEach(function(doc) { items[doc.id] = doc.data() }) cards.forEach(function(card, index) { let id = index let item1 = items[card.item1] let item2 = items[card.item2] let question = card.question.replace('?', ',') + '\n' + item1.item_name + ' o ' + item2.item_name + '?' cardComponents.push({id: id, image1: item1.image_url, image2: item2.image_url, question: question}) }) this.setState({cardComponents: cardComponents}) this.setState({cards: cards}) this.setState({items: items}) SplashScreen.hide() }.bind(this)) }.bind(this)) } render () { {this.state.cardComponents} }

StorageEvent

1 个答案:

答案 0 :(得分:2)

这是因为调用setState本质上是异步的。因此,在SplashScreen.hide()设置状态后,您的状态尚未正确更新。您有2个选择:

使用生命周期方法componentDidUpdate来检测您的状态是否已更新:

  componentDidUpdate(prevProps, prevState) {
    if (prevState.cardComponents !== this.state.cardComponents) {
      SplashScreen.hide();
    }
  }

使用setState方法中提供的回调:

this.setState({cardComponents: cardComponents}, () => { SplashScreen.hide(); })