Reactjs 异步componentDidMount未在React-native中执行
我正在尝试制作一个名为CacheImage的组件,它将把图像保存到缓存中。此组件接收url地址和样式作为参数,并返回具有特定url和样式的图像组件。我正在使用firebase存储来存储图像Reactjs 异步componentDidMount未在React-native中执行,reactjs,firebase,react-native,expo,Reactjs,Firebase,React Native,Expo,我正在尝试制作一个名为CacheImage的组件,它将把图像保存到缓存中。此组件接收url地址和样式作为参数,并返回具有特定url和样式的图像组件。我正在使用firebase存储来存储图像 import React from 'react'; import { Image } from 'react-native'; import shorthash from 'expo' import { FileSystem } from 'expo'; export default class Cach
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'/>;
}
}
从“React”导入React;
从“react native”导入{Image};
从“expo”导入shorthash
从“expo”导入{FileSystem};
导出默认类CacheImage扩展React.Component{
状态={
来源:null,
};
componentDidMount=async()=>{
const{uri}=this.props;
const name=shorthash.unique(uri);
警报(名称);
const path=`${FileSystem.cacheDirectory}${name}`;
const image=await FileSystem.getInfoAsync(路径);
if(image.exists){
警报(“从缓存读取图像”);
这是我的国家({
资料来源:{
uri:image.uri,
},
});
返回;
}
警报(“正在将图像下载到缓存”);
const newImage=await FileSystem.downloadsync(uri,路径);
这是我的国家({
资料来源:{
uri:newImage.uri,
},
});
};
render(){
返回;
}
}
但由于某些原因,程序甚至不会进入componentDidMount内部。我是react native的新手,所以我可能遗漏了一些明显的东西。有人能帮我吗?您可以创建一个异步函数,并在
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();
}
非常感谢,现在似乎正在运行:)