javascript - React Native 等待所有图像预取完成

标签 javascript react-native expo

我试图在导航到另一个屏幕之前预取多个图像,但返回的 Students 都未定义。

prepareStudentImages = async (students) => {
    let returnedStudents = students.map(student => {
        Image.prefetch(student.image)
        .then((data) => {
            ...
        })
        .catch((data) => {
            ...
        })
        .finally(() => {
            return student;
        });
    });

    await console.log(returnedStudents); // ----> all items undefined
}

最佳答案

有几个问题需要解决:

1) 你的 map()函数不返回任何东西。这就是为什么您的控制台日志是 undefined 的原因。

2) 一旦您的 map 函数起作用,您就会记录一组 promise 。要处理多个 promise (数组),您可以使用 Promise.all() .

所以我认为要解决这个问题,您可以这样做:

prepareStudentImages = async (students) => {
  const returnedStudents = students.map(student => 
    Image.prefetch(student.image)
      .then((data) => {
          ...
      })
      .catch((data) => {
          ...
      })
      .finally(() => {
          return student
      })
  )

  console.log(returnedStudents) // log the promise array

  const result = await Promise.all(returnedStudents) // wait until all asyncs are complete
  console.log(result) // log the results of each promise in an array

  return result
}

关于javascript - React Native 等待所有图像预取完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54060668/

相关文章:

android - React Native 应用程序中的 Redux 用例

image - React-native加载本 map 片有延迟

javascript - react 原生 : using redux saga eventChannel to externalise event listeners from components

ios - 使用 expo 构建的 React-native ios 应用程序使用发布返回错误 413

react-native - 'expo start -c' 实际执行什么命令?

javascript - Jquery 弹出 2 个许多警报和错误的坐标

固定在滚动条上的位置的javascript

javascript - Jquery post 的痛苦 jquery 错误

javascript - 如何在文件系统中获取最后修改日期和时间?

reactjs - 无法加载expo应用程序: Something went wrong