SetState 无法正常工作 React Native

SetState doesn't work properly React Native

我目前有以下代码:

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 数组中。

我已经使用下面类似的代码来填充“媒体”数组并且似乎没有遇到任何问题,这就是为什么我不知道为什么 setURLs 的代码不起作用。任何帮助将不胜感激!

 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}]);
    }
  };

setState()并不总是立即更新。

试试这个

//variable To Save Data Immediately.
const urlArray = [];

for (var i = 0; i < media.length; i++) {
    urlArray.push(yourDownloadUrl)
}

setUrls(urlArray);

doc

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.