加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

react-native – RNFS.exists()始终返回TRUE

发布时间:2020-12-15 20:16:05 所属栏目:百科 来源:网络整理
导读:我正在使用react-native-fs,出于某种原因,每当我使用exists()方法时,它总是返回为TRUE.我的代码示例如下所示: let path_name = RNFS.DocumentDirectoryPath + "/userdata/settings.json";if (RNFS.exists(path_name)){ console.log("FILE EXISTS") file = a
我正在使用react-native-fs,出于某种原因,每当我使用exists()方法时,它总是返回为TRUE.我的代码示例如下所示:

let path_name = RNFS.DocumentDirectoryPath + "/userdata/settings.json";

if (RNFS.exists(path_name)){
    console.log("FILE EXISTS")
    file = await RNFS.readFile(path_name)
    console.log(file)
    console.log("DONE")
}
else {
    console.log("FILE DOES NOT EXIST")
}

控制台的输出是“FILE EXISTS”,然后抛出一个错误,说:

Error: ENOENT: no such file or directory,open
/data/data/com.test7/files/userdata/settings.json’

如何使用exists方法存在,而不是readFile方法?

在进一步检查时,无论文件名是什么,RNFS.exists()似乎总是返回true.为什么它总是回归真实?

path_name的显示为/data/data/com.test7/files/userdata/settings.json.

即使我将代码更改为无意义的代码,如下面的代码:

if (RNFS.exists("blah")){
    console.log("BLAH EXISTS");
} else {
    console.log("BLAH DOES NOT EXIST");
}

它仍然评估为true并显示消息:

BLAH EXISTS

我已经显示了目录的内容并验证了这些文件不存在.

解决方法

那是因为 RNFS.exists()返回了一个Promise.将一个Promise对象放在if语句的测试中,它总是为true.

改为:

if (await RNFS.exists("blah")){
    console.log("BLAH EXISTS");
} else {
    console.log("BLAH DOES NOT EXIST");
}

要么:

RNFS.exists("blah")
    .then( (exists) => {
        if (exists) {
            console.log("BLAH EXISTS");
        } else {
            console.log("BLAH DOES NOT EXIST");
        }
    });

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读