所以,我需要做的是在加载应用程序时从本地文件夹加载图像。因此,我尝试通过以下方式实现此目的:
async function _cacheResourcesAsync() {
return new Promise(async (resolve) => {
resolve();
const images = [
require("whatever"),
require("whatever"),
require("whatever"),
require("whatever"),
]
const cacheImages = images.map(image => {
return Asset.fromModule(image).downloadAsync();
})
});
}
const App = () => {
const [isLoaded, setIsLoaded] = useState(false);
if (!isLoaded) {
return (
<AppLoading
startAsync={_cacheResourcesAsync}
onFinish={() => setIsLoaded(true)}
onError={console.warn}
/>
)
} else {
return Whatever
}
}
但是这是行不通的,我不太理解如何稍后在代码中使用这些图像,因为仅在_cacheResourcesAsync函数中声明了带有它们的数组。我在做什么错了?
答案 0 :(得分:1)
博览会: 这是工作的官方例子
import React from 'react';
import { Image, Text, View } from 'react-native';
import { Asset } from 'expo-asset';
import { AppLoading } from 'expo';
export default class App extends React.Component {
state = {
isReady: false,
};
render() {
if (!this.state.isReady) {
return (
<AppLoading
startAsync={this._cacheResourcesAsync}
onFinish={() => this.setState({ isReady: true })}
onError={console.warn}
/>
); }
return (
<View style={{ flex: 1 }}>
<Image source={require('./assets/snack-icon.png')} />
</View>
);
}
async _cacheResourcesAsync() {
const images = [require('./assets/snack-icon.png')];
const cacheImages = images.map(image => {
return Asset.fromModule(image).downloadAsync();
});
return Promise.all(cacheImages);
}
}
对于React Native,我建议使用类似的可靠解决方案