SetState 无法正常工作 React Native
2021-07-24
98
我目前有以下代码:
const uploadImage = async () => {
console.log('Hello2');
console.log(media.length);
for (var i = 0; i < media.length; i++) {
const image = media[i];
const uri = image.source;
const response = await fetch(uri);
const blob = await response.blob();
const storageRef = storage
.ref()
.child(`listing/${auth.currentUser.uid}/${Math.random().toString(36)}`);
const task = await storageRef.put(blob);
const downloadUrl = await task.ref.getDownloadURL();
console.log('download URL is:');
console.log(downloadURL);
setUrls([...urls, downloadURL]);
console.log('url added');
console.log(urls.length);
}
console.log('Process finished');
console.log(urls.length);
if (urls.length == media.length) {
alert('All images uploaded');
}
};
在此函数中,我本质上是尝试填充我的“urls”数组,但是不知何故,每当我运行代码时,它似乎都不会填充 urls 数组。在控制台记录所有内容时,问题不是 downloadURL,因为我获得了一个有效值,但不知何故没有任何东西添加到 urls 数组中。
我使用以下类似代码填充“media”数组,似乎没有任何问题,这就是为什么我不知道 setURL 的代码为什么不起作用。任何帮助都将不胜感激!
const openLibrary = async () => {
const {status} = await ImagePicker.requestMediaLibraryPermissionsAsync();
if (status !== 'granted') {
alert('Sorry, we need camera roll permissions to make this work!');
}
const image = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
console.log(image);
// console.log('Media length is: ' + `${media.length().toString()}`);
if (!image.cancelled) {
// console.log('Media length is: ' + media.length());
console.log('Hello');
setMedia([...media, {source: image.uri, type: image.type}]);
}
};
1个回答
setState()
并不总是立即更新。
试试这个
//variable To Save Data Immediately.
const urlArray = [];
for (var i = 0; i < media.length; i++) {
urlArray.push(yourDownloadUrl)
}
setUrls(urlArray);
文档 说
setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, read about the updater argument below.
Ahmed Gaber
2021-07-24