Не могу отобразить файлы jpg из кеша моего приложения Android React-NativeAndroid

Форум для тех, кто программирует под Android
Ответить
Anonymous
 Не могу отобразить файлы jpg из кеша моего приложения Android React-Native

Сообщение Anonymous »

Я пытаюсь чередовать отображение изображений Reddit и .jpg кэша. Либо не вижу других изображений, либо они полностью игнорируются, и я вижу только картинки Reddit ... пожалуйста, помогите мне решить эту проблему, у меня болит головные боли, лол < /p>
useEffect(() => {
console.log('Fetching cached images...');
const fetchCachedImages = async () => {
try {
const cacheDir = RNFS.CachesDirectoryPath;
const files = await RNFS.readDir(cacheDir);
const jpegFiles = files.filter(file => file.name.endsWith('.jpg')).map(file => `file://${file.path}`);
setCachedImages(jpegFiles);
console.log('Fetched cached images:', jpegFiles);
} catch (error) {
console.error('Error fetching cached images:', error);
}
};
fetchCachedImages();
}, []);

useEffect(() => {
console.log('Combining Reddit memes and cached images...');
const combined = [];
let redditIndex = 0;
let cachedIndex = 0;
let addReddit = true; // Flag to alternate between Reddit and cached memes

// Limit to first 100 memes
const maxMemes = 100;

// Ensure that we only use 100 memes from both Reddit and cache
while ((redditIndex < memes.length && combined.length < maxMemes) ||
(cachedIndex < cachedImages.length && combined.length < maxMemes)) {
if (addReddit && redditIndex < memes.length && combined.length < maxMemes) {
combined.push({ type: 'reddit', meme: memes[redditIndex] });
console.log(`Added Reddit meme at index ${redditIndex}`);
redditIndex++;
} else if (!addReddit && cachedIndex < cachedImages.length && combined.length < maxMemes) {
combined.push({ type: 'cache', meme: cachedImages[cachedIndex] });
console.log(`Added cached image at index ${cachedIndex}`);
cachedIndex++;
}
addReddit = !addReddit; // Alternate between Reddit and cache
}

setCombinedMemes(combined);
console.log('Combined memes (first 100):', combined);

// Réinitialisation de l'index à 1 lorsque les memes sont combinés
setCurrentIndex(1);
}, [memes, cachedImages]);

useEffect(() => {
console.log('Loading combined memes...');
const loadIndex = async () => {
const storedIndex = await AsyncStorage.getItem('currentIndex');
if (storedIndex) {
setCurrentIndex(parseInt(storedIndex));
} else {
// Si aucun index stocké, initialiser à 1
setCurrentIndex(1);
}
};
loadIndex();
}, []);
< /code>
Мне удалось получить кэшированные изображения и мемы Reddit отдельно, но я изо всех сил пытаюсь правильно чередовать их.
Приложение показывает только одно кэшированное изображение в комбинированном массиве, Несмотря на то, что в каталоге есть несколько кэшированных изображений.>

Подробнее здесь: https://stackoverflow.com/questions/793 ... act-native
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Android»