Error: `FileSystem.moveAsync` needs a `to` path. in react native (Expo)

Error: `FileSystem.moveAsync` needs a `to` path. in react native (Expo)

我正在尝试从真实设备拍摄照片并使用 expo expo-file-system 将其保存在新位置。但是我收到一个错误 Error: FileSystem.moveAsync needs a to path.

我的代码:

const fileMoveHandler = async () => {
    const fileName = selectedImage.split("/").pop();
    console.log("FileSystem:", FileSystem.documentDirectory + fileName);
    setNewPathImage(FileSystem.documentDirectory + fileName);
    console.log("newPathImage", newPathImage);
    try {
      await FileSystem.moveAsync({
        from: selectedImage,
        to: newPathImage,
      });
    } catch (err) {
      console.log("Error:", err);
      Alert.alert("Can't move this file.", "Try again!", [{ text: "Okay" }]);
    }
  };

Console.log:

FileSystem: file:///data/user/0/host.exp.exponent/files/ExperienceData/******/3061c494-6c3b-4307-abb3-a0d8681d2bb3.jpg

newPathImage undefined

Error: [Error: `FileSystem.moveAsync` needs a `to` path.]

因为我得到 newPathImage undefined 这就是为什么它给我错误但我不知道为什么我得到 undefined?

如何设置图片路径的状态?

一定是因为 setState() 是异步的,所以当您尝试将 to 设置为 newPathImage 时,它仍然未定义。如果您改为执行以下操作,它应该会起作用:

const fileMoveHandler = async () => {
    const fileName = selectedImage.split("/").pop();
    const newPathImage = FileSystem.documentDirectory + fileName
    console.log("FileSystem:", newPathImage);
    setNewPathImage(newPathImage);
    console.log("newPathImage", newPathImage);
    try {
      await FileSystem.moveAsync({
        from: selectedImage,
        to: newPathImage,
      });
    } catch (err) {
      console.log("Error:", err);
      Alert.alert("Can't move this file.", "Try again!", [{ text: "Okay" }]);
    }
  };