使用 expo 将图片保存到媒体库时出现问题

use*_*710 1 javascript promise react-native expo

我对反应和本机反应都是完全陌生的,但我正在努力学习它。

当我尝试将图片保存到手机图库时遇到问题

所以,我正在导入

import { MediaLibrary } from 'expo-media-library'
Run Code Online (Sandbox Code Playgroud)

我也在使用州

const [hasPermission, setHasPermission] = useState(null);
const [type, setType] = useState(Camera.Constants.Type.back);
const [cameraRef, setCameraRef] = useState(null)
Run Code Online (Sandbox Code Playgroud)

除了保存照片之外,一切正常

<TouchableOpacity style={{alignSelf: 'center'}} onPress={async() => {
            if(cameraRef){
              let photo = await cameraRef.takePictureAsync();
              console.log('photo', photo);
              MediaLibrary.saveToLibraryAsync(photo.uri)

            }
          }}>
Run Code Online (Sandbox Code Playgroud)

在我的控制台日志中我看到了该对象

    photo Object {
     "height": 4156,
     "uri": "file:///var/mobile/Containers/Data/Application/B7CCEDB6-DFC5-4898-BD70-B2FF1159FC1B/Library/Caches/ExponentExperienceData/%2540anonymous%252Ftest-5bfa90d8-12e9-44fe-a19d-69bb5eeb74b9/Camera/D783C734-29B9-489B-9798-A0737388E93C.jpg",
     "width": 2376,
}
Run Code Online (Sandbox Code Playgroud)

但我无法找到将其保存到相机胶卷的方法,我总是收到此错误

[Unhandled promise rejection: TypeError: undefined is not an object (evaluating '_expoMediaLibrary.MediaLibrary.saveToLibraryAsync')]
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激

R。

小智 5

我认为您在 Promise 中遇到了未定义对象错误,因为您也不MediaLibrary.saveToLibraryAsync()关心await.

您也许应该像在 takePictureAsync() 上所做的那样放置MediaLibrary.saveToLibraryAsync()with ,因为它是一个异步函数。await

let photo = await cameraRef.takePictureAsync();
console.log('photo', photo);
await MediaLibrary.saveToLibraryAsync(photo.uri);
Run Code Online (Sandbox Code Playgroud)

只是一个假设,希望能帮助你解决这个问题。