问题描述
我正在创建一个本机应用程序以使用expo-camera模块。
所以我将相机变量声明为
let camera: any = null;
我正在 通过 返回 将此内容的引用 传递为:
<Camera style = {{flex: 1,opacity: camOpacity}}
type = {state.type}
ratio = "2:1"
ref = {async (ref) => (camera = ref)}>
但是当我运行该应用程序时,它可以正常启动,但是在尝试拍照时会出现错误:
[Unhandled promise rejection: TypeError: null is not an object (evaluating 'camera.pictureSize')]
此错误来自:
console.log(camera.pictureSize);
但是它也在发生:
console.log(" --> Taking image");
const opts = {
skipProcessing: true,exif: false,quality: 0
};
let photo = await camera.takePictureAsync(opts);
当我注释console.log(camera.pictureSize); 时,从 camera.takePictureAsync(opts)部分中
由于某种原因,引用可能没有被检测到。
我的package.json是:
"dependencies": {
"expo": "~39.0.2","expo-2d-context": "0.0.2","expo-asset": "~8.2.0","expo-camera": "~9.0.0","expo-gl": "~9.1.1","expo-image-manipulator": "~8.3.0","expo-permissions": "~9.3.0","react": "16.13.1","react-dom": "16.13.1","react-native": "https://github.com/expo/react-native/archive/sdk-39.0.3.tar.gz","react-native-web": "~0.13.12","react-native-screens": "~2.10.1","react-native-svg": "~12.1.0","mem": "^8.0.0","@unimodules/core": "~5.5.0"
}
我读到当前的Expo-camera版本中存在一些此类错误,但是即使我降级了软件包和依赖项,它仍然持续存在。
任何帮助将不胜感激。
编辑:
const photo = async (): Promise<CameraCapturedPicture> | undefined => {
if(camera){
console.log(" --> Taking image");
const opts = {
skipProcessing: true,quality: 0
};
return await camera.takePictureAsync(opts);
}
}
console.log(" --> Resizing image");
const {uri} = await ImageManipulator.manipulateAsync(
photo.uri,[
{ resize: {width: 256,height: 512}},{ crop: {originX: 0,originY: 128,width: 256,height: 256}}
]
);
我根据Linda的建议更改了代码,但现在的错误是Promise不是有效的类型,并且 photo.uri 没有 uri 属性>
解决方法
您已将camera
引用对象初始化为null
。因此,在对其调用任何函数之前,需要验证它实际上是否已设置为Camera
,但仍不是null
。我怀疑这是您拍照功能出错的原因。请注意in the docs,他们在调用相机上的方法之前检查了if (this.camera) {
。
console.log(camera.pictureSize)
, null
也是错误的,因为该属性不存在。 pictureSize
是一个传递给Camera
组件的道具。它不是相机实例上存在的属性。您应该review the documentation。
您可以将变量声明更改为any
,而不是使用Camera | null
,这将有助于您查看可用的属性和方法。
let camera: Camera | null = null;
您可以在调用拍照方法内检查camera
是否不是null
:
const takePicture = async (): Promise<CameraCapturedPicture> | undefined => {
if (camera) {
console.log(" --> Taking image");
const opts = {
skipProcessing: true,exif: false,quality: 0
};
return await camera.takePictureAsync(opts);
}
};
或者您可以在调用该方法之前进行检查,并将camera
变量传递给该方法,以便打字稿知道它不是null
。
const executeTakePicture = async (cam: Camera): Promise<CameraCapturedPicture> => {
console.log(" --> Taking image");
const opts = {
skipProcessing: true,quality: 0
};
return await cam.takePictureAsync(opts);
};
const maybeTakePicture = async (): Promise<CameraCapturedPicture> | undefined => {
if (camera) {
return await executeTakePicture(camera);
} else {
//...
}
}