react-native-image-picker response.uri 未定义

react-native-image-picker response.uri is undefined

在我的 react-native 应用程序中,我使用 react-native-image-picker 从相机或图库中选择图像。但是 resource.urilaunchCameralaunchImageLibrary 中都在 undefined 中返回。我做错了什么?

这是我的 github repo 反应本机应用程序的基本构建。图像选择器代码在 addProductScreen.js

我看到了你的问题,我有一个解决方案给你。 响应是一个 JSON 对象,其中包含一个名为 assets 的数组 这样您就可以使用它访问您的图像 url。

response.assets[0].uri

这对我有帮助,我可以解释一下原因!

response 是一个 JSON 对象,它包含一个名为 assets.

的数组

要访问数组的第一个元素,请使用 .assets[0],然后您可以访问 .uri.fileName 等。

{
  //response.uri is looking for the uri right here instead of inside assets[]
  "assets": [
    {
      "fileName": "yourImage.jpg",
      "fileSize": 123,
      "height": 123,
      "type": "image/jpeg",
      "uri": "yourImage.jpg",
      "width": 123
    }
  ]
}

根据以上答案,这适用于:

const handleSelectImage = () => {
    const options = {
      noData: true,
      mediaType: 'photo' as const
    }
    launchImageLibrary(options, (response) => {
      if (response.assets) {
        const imageAssetsArray = response.assets[0].uri
        setImageState(imageAssetsArray)
      }
    })
}

我也在为这个问题挠头。我写了一个函数来测试从我的照片选择中返回了什么对象:

    launchCamera(options, (response) => {
      if (response.assets && response.assets?.length !== 0) {
        setFilePath(response.assets[0].uri)
        console.log('ASSET OBJECT FOUND: ', response.assets[0].uri)
        return
      } else if (response.uri) {
        setFilePath(response.uri)
        console.log('NO ASSET OBJECT FOUND: ', response.uri)
        return
      } else if (response.didCancel) {
        return
      } else if (response.errorCode === 'camera_unavailable') {
        setNoCameraFound(true)
        return
      } else {
        setNeedsCameraAccess(true)
        return
      }
    })

使用我的 iPhone 时,Asset 对象未定义,但在我的 Android 上它就在那里。如果您使用的是 TypeScript,它会抱怨 response.uri 除非您将该值添加到 types.d.ts

    didCancel?: boolean;
    errorCode?: ErrorCode;
    errorMessage?: string;
    assets?: Asset[];
    uri?: string;
}