【问题标题】:React Native async (firebase) image fetch in ScrollView / FlatList / SectionList在 ScrollView / FlatList / SectionList 中反应原生异步(firebase)图像获取
【发布时间】:2017-07-06 08:13:54
【问题描述】:

我有一个 SectionList,其中包含许多从 firebase 存储中获取的图像。向下滚动时,它会迅速生成大量警告。

WebImage 组件如下所示:

import React, { Component } from 'react'
import { View, Image } from 'react-native'
import firebase from 'firebase'

class WebImage extends Component {
  state = {
    imgsrc: '',
    mounted: false,
  }

  componentDidMount() {
    this.setState({ mounted: true })

    firebase
      .storage()
      .ref()
      .child(this.props.source)
      .getDownloadURL()
      .then(url => {
        if (this.state.mounted) {
          this.setState({ imgsrc: url })
        }
      })
  }

  componentWillUnmount() {
    this.setState({ mounted: false })
  }

  render() {
    ...
  }
}

export default WebImage

如你所见,我试图让它知道安装状态,但它没有按预期工作..

【问题讨论】:

    标签: reactjs firebase asynchronous react-native firebase-storage


    【解决方案1】:

    以下似乎有效:

      state = {
        imgsrc: '',
      }
    
      componentDidMount() {
        this.ref = firebase
          .storage()
          .ref()
          .child(this.props.source)
          .getDownloadURL()
          .then(url => {
            this.setState({ imgsrc: url })
          })
      }
    
      componentWillUnmount() {
        this.ref.cancel()
      }
    

    阅读latest on Async React 并将我的答案从componentWillMount 更改为componentDidMount

    有一个常见的误解,即在 componentWillMount 中获取可以让您避免第一个空渲染状态。实际上,这从来都不是真的,因为 React 总是在 componentWillMount 之后立即执行渲染。如果在 componentWillMount 触发时数据不可用,则无论您在哪里启动获取,第一个渲染仍将显示加载状态。这就是为什么在绝大多数情况下将 fetch 移动到 componentDidMount 没有明显的效果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-08
      • 2018-12-02
      • 1970-01-01
      相关资源
      最近更新 更多