【发布时间】:2018-02-14 15:11:38
【问题描述】:
我正在尝试获取所有图像(userPics 等)并将 Base64 字符串存储在我的 Redux 存储中(以便我可以离线使用它们)。因此,我在渲染之前在应用程序开始时加载/获取这些图像。我使用redux-thunk,所以我可以调度一个动作(获取,返回一个Promise)然后(.then())调度来存储它们。
但是,并非所有图像都在渲染之前存储(尽管我很确定我声明了 Promise(s) 正确)。这是我的缓存(用于图像)reducer(包括获取操作):
const initialState = {
images: [],
}
//Reducer
export default (state = initialState, action) => {
let index, images;
images = state.images.slice();
index = images.findIndex(x => x.url===action.url);
switch (action.type){
//Store images
case STORE_IMAGE:
if( index === -1){
images.push({url:action.url,
img: action.img,
width: action.width,
height: action.height});
}else{
images[index] = {url:action.url,
img: action.img,
width: action.width,
height: action.height};
}
return {
...state,
images: images
}
default:
return state
}
}
//ARE THERE SIDE EFFECTS?
export const storeImage = (url, img, width, height) => {
return dispatch =>
dispatch({
type: STORE_IMAGE,
url: url,
img: img,
width: width,
height: height
});
}
//Fetch, returns Promise (used to render when resolved)
export const cacheImage = (url) => {
return dispatch => new Promise((resolve, reject) => {
//test if images is already fetched
let images = store.getState().cache.images;
let index = images.findIndex(x => x.url===url);
if(index === -1){
let mimeType = mime.lookup(url.split("?")[0]);
RNFetchBlob.fetch('GET', url)
.then((response) => {
let base64Str = response.data;
var imageBase64 = 'data:'+mimeType+';base64,'+base64Str;
// Get resolution
Image.getSize(imageBase64, (width, height) => {
// Store base64 image
dispatch(storeImage(url, imageBase64, width, height));
resolve(imageBase64);
});
}).catch((error) => {
// error handling
reject(error);
});
}else{
//already fetched
resolve(images[index].img);
}
});
}
如果我包含一个 setTimeout() 以在足够的时间内解决 Promise(在 Images.getSize 中),则所有图像都会在渲染之前存储。这让我很奇怪,因为我认为内部的dispatch(storeImage) 是一个没有副作用的函数(至少应该是)?!我不能再做出另一个承诺,对吧?
【问题讨论】:
标签: reactjs react-native redux react-redux redux-thunk