【发布时间】:2021-04-06 21:32:53
【问题描述】:
我在保存我在我的 react 本机应用程序中选择的图片的 uri 时遇到了一点问题。
以下代码示例至关重要:
const ProfileScreen = props =>{
const [pickedImage, setPickedImage] = useState(null);
const [modalVisible, setModalVisible] = useState(false); //State for visible Modal
const [userBio, setUserBio] = useState('Useless Placeholder'); //State for users text in the bio
const verifyPermissions = async () => { //ask for permissions on iOS and Android
const result = await Permissions.askAsync(Permissions.CAMERA_ROLL);
if (result.status !== 'granted'){
Alert.alert("Insufficient permissions!", "You need to grant galery permissions to customise your profile picture!", [{text: "Got it."}]);
return false;
};
return true;
};
const takeImageHandler = async () => { //function that opens up the camera
const hasPermission = await verifyPermissions();
if (!hasPermission){
return;
}
const image = await ImagePicker.launchImageLibraryAsync({
allowsEditing: true,
quality: 0.5,
aspect: [16,16]
});
setPickedImage(image.uri);
console.log("Data raw is: " + image.uri);
console.log("Data from hook is: " + pickedImage);
};
if(userBio.length == 0 && modalVisible == false){
setUserBio("Useless Placeholder");
};
如您所见,我有 2 个控制台日志来检查我的结果。我想将 image.uri 保存到我在 ProfileScreen 顶部声明的钩子中。问题是我在控制台中得到的输出:
原始数据为: 文件:/data/user/0/host.exp.exponent/cache/ExperienceData/%2540kubaguette%252FPigeonBuddy/ImagePicker/30953995-840b-451e-a505-6082df16b9e3.jpg 来自钩子的数据是:null
为什么setPickedImage(image.uri) 在这里不起作用? 为什么我可以console.log我所选图片的uri,但不能将此uri保存到我的钩子并检索它?
【问题讨论】:
-
takeImageHandler 是一个异步函数,它将pickImage 的值保存在闭包中。在渲染中设置控制台而不是 takeImageHandler 方法并验证。
标签: reactjs react-native react-redux expo