Я пытаюсь чередовать отображение изображений 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
Не могу отобразить файлы jpg из кеша моего приложения Android React-Native ⇐ Android
Форум для тех, кто программирует под Android
1737745415
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 отдельно, но я изо всех сил пытаюсь правильно чередовать их.
Приложение показывает только одно кэшированное изображение в комбинированном массиве, Несмотря на то, что в каталоге есть несколько кэшированных изображений.>
Подробнее здесь: [url]https://stackoverflow.com/questions/79385373/cant-display-jpg-files-from-the-cache-of-my-app-android-react-native[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия