【问题标题】:async componentDidMount not executing in React native异步 componentDidMount 未在 React Native 中执行
【发布时间】:2021-04-21 12:31:17
【问题描述】:

我正在尝试制作名为 CacheImage 的组件,它将图像保存到缓存中。该组件接收 url 地址style 作为参数,并返回具有特定 url 和样式的 Image 组件。我正在使用 Firebase 存储来存储图像。

import React from 'react';
import { Image } from 'react-native';
import shorthash from 'expo'
import { FileSystem } from 'expo';

export default class CacheImage extends React.Component {
  state = {
    source: null,
  };

  componentDidMount = async () => {
    const { uri } = this.props;
    const name = shorthash.unique(uri);
    alert(name);
    const path = `${FileSystem.cacheDirectory}${name}`;
    const image = await FileSystem.getInfoAsync(path);
    if (image.exists) {
      alert('read image from cache');
      this.setState({
        source: {
          uri: image.uri,
        },
      });
      return;
    }

    alert('downloading image to cache');
    const newImage = await FileSystem.downloadAsync(uri, path);
    this.setState({
      source: {
        uri: newImage.uri,
      },
    });
  };

  render() {
    return <Image style={this.props.style} source={this.state.source} resizeMode='cover'/>;
  }
}

但由于某种原因,程序甚至不会进入 componentDidMount。我是本机反应的新手,所以也许我遗漏了一些明显的东西。谁能帮帮我?

【问题讨论】:

    标签: reactjs firebase react-native expo


    【解决方案1】:

    您可以创建一个异步函数并在componentDidMount 中调用它。

    componentDidMount() {
        const asyncFunction = async () => {
          const { uri } = this.props;
          const name = shorthash.unique(uri);
          alert(name);
          const path = `${FileSystem.cacheDirectory}${name}`;
          const image = await FileSystem.getInfoAsync(path);
          if (image.exists) {
            alert('read image from cache');
            this.setState({
              source: {
                uri: image.uri,
              },
            });
            return;
          }
    
          alert('downloading image to cache');
          const newImage = await FileSystem.downloadAsync(uri, path);
          this.setState({
            source: {
              uri: newImage.uri,
            },
          });
        };
    
        asyncFunction();
      }
    

    【讨论】:

    • 非常感谢,现在好像可以使用了 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-10
    • 1970-01-01
    • 2023-03-26
    • 2016-11-13
    • 1970-01-01
    • 2021-06-25
    • 1970-01-01
    相关资源
    最近更新 更多