javascript - React Native:未定义不是对象(评估'_ref.photo')
问题描述
我必须使用 制作一个相机应用程序expo-camera
,并且我经历了这个错误_ref.photo is undefined
。我的整个代码中没有 _ref.photo,但我photo
在上下文中有一个变量。
我的背景:
type CameraShot = CameraCapturedPicture | undefined;
export type AccountContextType = {
photo: CameraShot;
setPhoto: (photo: CameraShot) => void;
};
export const AccountContext = React.createContext<
AccountContextType | undefined
>(undefined);
const AccountProvider = ({ children }) => {
const [photo, setPhoto] = React.useState<CameraShot>(undefined);
return (
<AccountContext.Provider
value={{
photo,
setPhoto
}}
>
{ children }
</AccountContext.Provider>
);
};
export default AccountProvider;
我的相机功能:
const { photo, setPhoto } = useContext(AccountContext) as AccountContextType;
let _camera = useRef<Camera | null>();
const [isBackCam, setIfBackCam] = useState(false);
const [status, setStatus] = useState(undefined as unknown);
const [isCamReady, setIfCamReady] = useState(false);
const [isPreviewModalShown, setIfPreviewModalShown] = useState(false);
useEffect(() => {
Camera.getCameraPermissionsAsync()
.then((response) => setStatus(response.status));
}, []);
return (
<View>
{status === 'granted' ? (
<>
<Camera
ratio="1:1"
ref={e => _camera.current = e}
onCameraReady={() => setIfCamReady(true)}
type={isBackCam ? Camera.Constants.Type.back : Camera.Constants.Type.front}
style={{ display: 'flex', height: '100%' }}
>
<View style={{ flex: 1, width: '100%', flexDirection: 'row' }}>
<Text
onPress={() => setIfBackCam(e => !e)}
style={styles.shootText}
> Flip </Text>
<Text
onPress={() => {
if (_camera && isCamReady) {
_camera.current?.takePictureAsync()
.then((response) => setPhoto(response))
return setIfPreviewModalShown(true);
}
}}
style={styles.shootText}> Shoot </Text>
</View>
</Camera>
<Modal isVisible={isPreviewModalShown}>
{photo !== undefined && (
<View style={{ backgroundColor: colors.background }}>
<Image
source={{ uri: photo.uri }}
height={photo.height}
width={photo.width}
/>
</View>
)}
</Modal>
</>
) : (
<View style={{ margin: 15 }}>
<Title extraLarge title='Accès refusé' />
<Text style={{ marginTop: '70%', alignSelf: 'center' }}> Veuillez accorder l'accès à l'appareil photo </Text>
<Spacer vertical />
<Button
innerText="Accorder l'accès"
onPress={() => {
Camera.requestCameraPermissionsAsync()
.then((response) => setStatus(response.status));
}}
/>
</View>
)}
</View>
);
我认为这是一个上下文问题,但我没有设法解决这个问题。你们能帮帮我吗?什么是未定义的,我该如何解决这个问题?
谢谢 !
解决方案
推荐阅读
- hive - Hive Bucketing:不同列值的数量大于桶数的数量
- python - 如何将单列的数据拆分为成对的列
- python - Python 软 tf-idf 函数
- azure - 在 Azure Web 服务中执行 python 脚本时出现错误 0085,但在 ML 实验中没有
- angular - Angular 8 - 仅在组件内显示加载微调器
- c# - 任何其他可用于 http 触发功能应用程序的替代代码读取服务总线消息不想使用服务总线触发器
- asp.net - 实体框架抛出无法插入空值异常
- ios - iOS 中控制反转的框架和静态库有何不同?
- node.js - 使用 try 和 catch 扭曲 Nodejs 中的索引文件
- python - 如果与数据框中的给定列表相同,则分配标签值