【问题标题】:json file not updating in react nativejson文件未在本机反应中更新
【发布时间】:2020-06-19 13:15:09
【问题描述】:

我想写入一个 JSON 文件,所以我使用了react-native-fs 这是代码:

const add = (n, p, pr) => {
    var RNFS = require('react-native-fs');

    var filePath = RNFS.DocumentDirectoryPath + '/items.json';

    RNFS.writeFile(filePath, '{name:hello}', 'utf8')
      .then((success) => {
        console.log('SUCCESS');
      })
      .catch((err) => {
        console.log(err.message);
      });
  };

它记录成功但没有更新文件任何想法?

【问题讨论】:

    标签: json react-native react-native-fs


    【解决方案1】:

    您的文件正在成功更新,如果您想检查它,请在您的文件写入后运行以下代码。您将看到文件的路径和保存文件的数据。

    // get a list of files and directories in the main bundle
    RNFS.readDir(RNFS.DocumentDirectoryPath)
      .then((result) => {
        console.log('GOT RESULT', result);
    
        // stat the first file
        return Promise.all([RNFS.stat(result[0].path), result[0].path]);
      })
      .then((statResult) => {
        if (statResult[0].isFile()) {
          // if we have a file, read it
          return RNFS.readFile(statResult[1], 'utf8');
        }
    
        return 'no file';
      })
      .then((contents) => {
        // log the file contents
        console.log("contents");
        console.log(contents); // You will see the updated content here which is "{name:hello}"
      })
      .catch((err) => {
        console.log(err.message, err.code);
      });
    

    【讨论】:

    • 它工作我可以看到我写入文件的内容,但无法在任何地方找到文件这是它记录的 [{"ctime": null, "isDirectory": [Function isDirectory], "isFile": [Function isFile], "mtime": 2020-06-19T19:07:30.000Z, "name": "items.json", "path": "/data/data/com.shoppinglist/files/items.json", "size": 12}, {"ctime": null, "isDirectory": [Function isDirectory], "isFile": [Function isFile], "mtime": 2020-06-19T19:00:30.000Z, "name": "ReactNativeDevBundle.js", "path": "/data/data/com.shoppinglist/files/ReactNativeDevBundle.js", "size": 5831985}] 路径在我的电脑上没有退出
    • 兄弟,您也可以查看this answer 来查找您的文件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    • 2018-07-16
    • 2020-05-04
    • 2021-10-01
    相关资源
    最近更新 更多