在导航到组件之前预加载图像 [英] Preload images before navigating to component

查看:23
本文介绍了在导航到组件之前预加载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这更像是一个概念性问题,但我不确定解决它的确切方法.

This is more of a conceptional question, but I am not sure the exact way to solve it.

我有一个要从中下载图像的组件,但我希望能够指示该组件已加载,然后用户才能使用路由器通量切换到该组件.

I have a component I want to download images from, but I want to be able to indicate that the component is loaded before the user can then use router flux to switch to it.

我猜这是我必须在 redux 中完成的事情,这是正确的想法吗?我一直在尝试寻找一个可以执行此操作的 React Native 应用程序示例.

I am guessing that is something I would have to accomplish in redux, is that the right idea? I've been trying to find an example of a react native app that does this.

非常感谢!

推荐答案

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

RN Image component a specific static method to handle this case: https://facebook.github.io/react-native/docs/image.html#prefetch

注意:Image.prefetch 返回一个 Promise

Note: Image.prefetch returns a Promise

以下是如何使用 React Native Router Flux (RNRF) 实现此功能的示例,而不使用 Redux:

Below is an example of how to implement this using React Native Router Flux (RNRF), without using Redux:

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 组件中像往常一样使用图像组件,图像将从本地磁盘缓存中获取,而不是远程获取:

Then in your someScene component use the image component like you normally do and the image will be fetched from your local disk cache rather then remotely :

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

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

Also just be aware you'll have issues if you attempt to load images from http rather than secured https endpoints: https://github.com/facebook/react-native/issues/8520

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

If you wanted to use it with Redux put the above code in an Action and make sure your reducers respond to the action and set the new state as per your application requirements.

这篇关于在导航到组件之前预加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆