【发布时间】:2021-08-27 09:00:15
【问题描述】:
我正在下载一些文件并将它们的数据保存到本地存储以进行本机反应。下载工作正常,但我试图将对象数据保存到数组并将数组存储在本地存储中。当我试图保存该项目时,问题就出现了。我必须单击两次下载按钮来保存项目,否则数组在本地存储中保持为空并且不会更新。
const [value, setValue] = useState(0);
const [initialElements, setinitialElements] = useState([]);
const [videoid, setvideoid] = useState(0);
//Downloading Video file
const downloadVideo = async () => {
RNFetchBlob.config({
fileCache: true,
appendExt: 'mp4',
}).fetch(
'GET',
'https://cdn.videvo.net/videvo_files/video/premium/getty_105/large_watermarked/istock-1083459308_preview'
).progress((received, total) => setValue(Math.round((received / total) * 100)).then(res => {
setvideopath(res.path());
console.log('Video Complete');
addElement();
});
};
const addElement = async () => {
let ItemData = {
itemKey: videoid,
itemName: 'Object ' + (videoid+ 1),
image: imgpath,
video: videopath,
};
//Pushing new object into array
var newArray = [...initialElements, ItemData];
setvideoid(videoid+ 1);
setinitialElements(newArray);
try {
await AsyncStorage.setItem('cachedvideos', JSON.stringify(initialElements));
} catch (error) {
// Error saving data
}
};
return (
<View>
<Button title="Download" onPress={downloadVideo}/>
<View style={{
alignItems: 'center',
marginTop: 25,
}}>
<AnimatedCircularProgress
size={25}
width={4}
fill={value}
tintColor="#00e0ff"
backgroundColor="#3d5875"
/>
</View>
</View>
);
我只需要使用要在另一个屏幕中使用的新对象来更新本地存储上的数组。
【问题讨论】:
标签: reactjs react-native caching react-hooks