reactjs - 异步 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。我是本机反应的新手,所以也许我遗漏了一些明显的东西。任何人都可以帮助我吗?
解决方案
您可以创建一个异步函数并在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();
}
推荐阅读
- google-apps-script - 将格式化文本从 Google 表格转换为 Google 文档
- sql - 使用 ALTER 添加新列后,数据错误地加载到 Hive 分区表中
- pandas - 查找随机交叉并通过secondary_y检查图上的值
- python - Ajax Django 添加按钮未在第一次单击时添加
- c++ - 抛出异常:读取访问冲突。this->callbacks 是 0xCDCDCDCD
- javascript - 查找数组中每个元素的出现次数,并根据出现次数以升序或降序排列它们
- node.js - 将 expo cli 升级到最新版本。我收到了这个错误
- javascript - 循环并求和 JSON 值
- python - 为 sklearn CountVectorizer 使用自定义词汇 n-gram
- windows-subsystem-for-linux - 您如何下载用于 WSL 离线安装的 ubuntu 发行版