图像选择器 - 使用 Hook

时间:2020-12-30 11:05:09

标签: reactjs react-native react-redux expo

我在保存我在 React Native 应用程序中选择的图片的 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 保存到我的挂钩并检索它?

1 个答案:

答案 0 :(得分:1)

setPickedImage 因为任何更新状态的方法本质上都是 async

如果这是唯一的问题,您可以使用 useEffect 跟踪更改。

useEffect(() => {
  console.log(pickedImage);
}, [pickedImage]);

您可以在这里看到不同之处:https://codesandbox.io/s/usestate-async-rnzox?file=/src/App.js