首页 > 解决方案 > 异步 componentDidMount 未在 React Native 中执行

问题描述

我正在尝试制作名为 CacheImage 的组件,它将图像保存到缓存中。该组件接收url 地址样式作为参数,并返回具有特定 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。我是本机反应的新手,所以也许我遗漏了一些明显的东西。任何人都可以帮助我吗?

标签: reactjsfirebasereact-nativeexpo

解决方案


您可以创建一个异步函数并在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();
  }

推荐阅读