使用Expo Camera拍摄照片后无法在个人资料页显示的问题
解决Expo相机拍照后图片无法在Image组件显示的问题
看起来你遇到的核心问题是Image组件的source属性格式不正确,另外代码里还有一个异步状态更新的小坑,我来一步步帮你解决:
1. 修复Image组件的Source格式
你的代码里直接把uri字符串传给了source属性,但Expo的Image组件要求本地文件的source必须是一个包含uri字段的对象,而不是字符串本身。修改你的TouchableOpacity里的Image代码:
<TouchableOpacity onPress={this.shotPhoto.bind(this)}> <Image source={this.props.userpicture != null ? { uri: this.props.userpicture } : require('../../images/resimyok.png')} /> <Text>Shot a Photo</Text> </TouchableOpacity>
这里把this.props.userpicture包装成{ uri: this.props.userpicture },这样就符合Image组件对source属性的要求了,那个“Invalid prop source”的警告应该就会消失。
2. 修复异步状态更新的路径错误
在你的takePicture方法里,还有一个容易忽略的问题:setState是异步操作,当你执行Actions.hesabim时,this.state.photoId还没有更新,不过你当前的路径其实是正确的(因为move用的是旧的photoId,传参也用旧的),但为了避免未来的bug,建议你提前保存当前的photoId值,避免依赖异步更新的state:
takePicture = async function() { if (this.camera) { const options = { quality: 0.5, base64: true }; // 提前保存当前的photoId,避免异步state更新导致的错误 const currentPhotoId = this.state.photoId; this.camera.takePictureAsync().then(data => { const targetPath = `${FileSystem.documentDirectory}photos/Photo_${currentPhotoId}.jpg`; FileSystem.moveAsync({ from: data.uri, to: targetPath, }).then(() => { this.setState({ photoId: currentPhotoId + 1 }); Vibration.vibrate(); Actions.hesabim({ userpicture: targetPath }); }); }); } };
这样不管setState什么时候完成,你都能准确传递正确的图片路径。
3. 额外检查点
- 确保
FileSystem.documentDirectory的路径正确,你可以在控制台打印targetPath确认是否和你预期的一致(比如你给出的file:///data/user/0/host.exp.exponent/files/ExperienceData/%2540programci.yilmaz%252Fkpbduser/photos/Photo_2.jpg)。 - 确认你已经在app.json中配置了正确的文件系统权限(Expo通常会自动处理,但如果有问题可以检查)。
按照这几步修改后,你的照片应该就能正常显示在个人资料页面了。
内容的提问来源于stack exchange,提问作者Engin Yilmaz
相关产品推荐
相关产品推荐

