Preload images before navigating to component

前端 未结 1 1191
轮回少年
轮回少年 2021-01-02 19:10

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 in

1条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-02 19:52

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

    Note: Image.prefetch returns a Promise

    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})
        }
    })
    

    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 :

     
    

    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

    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.

    0 讨论(0)
提交回复
热议问题