资源缓存
编辑页面
For the complete documentation index, see llms.txt. Use this Use this file to discover all available pages.
本节涵盖与在应用中加载资源相关的所有内容,从将资源与应用二进制文件打包,到缓存、预加载和发布。
将资源打包
将资源打包进你的二进制文件将提供最佳的用户体验,因为你的资源会立即可用。应用无需向 CDN 发起网络请求来获取已发布的资源,而是会从本地磁盘读取,从而带来更快、更高效的加载体验。资源打包还支持离线功能。
要将资源打包进你的二进制文件,请在 app.json 中使用 assetBundlePatterns 键,提供项目目录中的路径列表:
"assetBundlePatterns": [ "assets/images/*" ],
路径与给定模式匹配的图片将在你下次运行 eas build 时被打包进你的原生二进制文件。
注意:如果你的应用包含异常数量的资源,或者资源大小异常大,资源打包可能不是最佳方案,因为它会导致应用体积膨胀。在这种情况下,请有选择地打包那些必要的资源,并将其余资源存储在 CDN 上。
预加载和缓存资源
资源的缓存方式会因其存储位置和使用方式而异。本节提供最佳实践,以确保你只在需要时下载资源。为了在缓存资源时保持加载界面可见,建议在一切就绪之前渲染 SplashScreen。
要下载并缓存保存在本地文件系统中的图片,请使用 Asset.fromModule(image).downloadAsync()。对于带有远程 URL 的图片,请使用 Image.prefetch(image)。
字体通过 Font.loadAsync(font) 进行预加载。此方法中的 font 参数是一个对象,例如:{OpenSans: require('./assets/fonts/OpenSans.ttf')}。@expo/vector-icons 为此对象提供了一个便捷的快捷方式,如下例中的 FontAwesome.font:
import React, { useState, useEffect } from 'react'; import { View, Text, Image, StyleSheet } from 'react-native'; import * as SplashScreen from 'expo-splash-screen'; import * as Font from 'expo-font'; import { Asset } from 'expo-asset'; import FontAwesome from '@expo/vector-icons/FontAwesome'; function cacheImages(images) { return images.map(image => { if (typeof image === 'string') { return Image.prefetch(image); } else { return Asset.fromModule(image).downloadAsync(); } }); } function cacheFonts(fonts) { return fonts.map(font => Font.loadAsync(font)); } export default function App() { const [appIsReady, setAppIsReady] = useState(false); // 在渲染应用之前加载任何你需要的资源或数据 useEffect(() => { async function loadResourcesAndDataAsync() { try { SplashScreen.preventAutoHideAsync(); const imageAssets = cacheImages([ 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png', require('./assets/images/circle.jpg'), ]); const fontAssets = cacheFonts([FontAwesome.font]); await Promise.all([...imageAssets, ...fontAssets]); } catch (e) { // 你可能希望将这些错误信息提供给错误报告服务 console.warn(e); } finally { setAppIsReady(true); SplashScreen.hideAsync(); } } loadResourcesAndDataAsync(); }, []); if (!appIsReady) { return null; } return ( <View style={styles.container}> <Text>你好,世界,这是我的应用。</Text> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', }, });
要使用本地图片资源,你可以像平常一样在项目中继续引用该图片的源文件,例如:
<Image source={require('path/to/image.png')} />
完整可运行示例请参见 Expo 的 tabs 模板项目。你也可以运行 npx create-expo-app --template tabs 来使用相同模板创建本地项目。