【问题标题】:React Native preload local imagesReact Native 预加载本地图像
【发布时间】:2018-07-11 09:42:23
【问题描述】:

如何在 React Native 中渲染之前加载图像

我使用地图。

我使用自定义图像作为标记。

我想在加载地图之前(或在渲染之前)加载标记图像

【问题讨论】:

标签: react-native react-native-maps


【解决方案1】:

RN Image 组件一个特定的静态方法来处理这种情况:https://facebook.github.io/react-native/docs/image.html#prefetch

注意:Image.prefetch 返回一个 Promise

下面是一个示例,说明如何在不使用 Redux 的情况下使用 React Native Router Flux (RNRF) 实现这一点:

let urlOfImages = [https://...]

let preFetchTasks = []; 

urlOfImages.forEach((p)=>{
    preFetchTasks.push(Image.prefetch(p));
});

Promise.all(preFetchTasks).then((results)=>{
    let downloadedAll = true;
    results.forEach((result)=>{
        if(!result){
            //error occurred downloading a pic
            downloadedAll = false;
        }
    })

    if(downloadedAll){
        Actions.someScene({ downloadedPics: urlOfImages})
    }
})

然后在您的 someScene 组件中像往常一样使用图像组件,图像将从本地磁盘缓存中获取,而不是从远程获取:

 <Image style={...} source={{uri: this.props.urlOfImages[0]}} />

另外请注意,如果您尝试从 http 而不是安全的 https 端点加载图像,则会遇到问题:https://github.com/facebook/react-native/issues/8520

如果您想将它与 Redux 一起使用,请将上述代码放在一个 Action 中,并确保您的 reducer 响应该操作并根据您的应用程序要求设置新状态。

资源:https://stackoverflow.com/a/42710306/6569224

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-21
    • 1970-01-01
    • 2016-05-17
    • 2015-12-24
    • 1970-01-01
    • 1970-01-01
    • 2019-05-15
    相关资源
    最近更新 更多