【问题标题】:Reading Json file with RNFS on react native使用 RNFS 在本机反应上读取 Json 文件
【发布时间】:2018-09-21 02:01:03
【问题描述】:

我正在尝试访问我刚刚使用 RNFS 编写的 JSON 文件的内容。 我尝试了不同的方法,导入、json-loader 等都没有成功。

我这样写文件:

    var obj = {
    date: moment().format(),
    counter: 0 };
    var json = JSON.stringify(obj);
    RNFS.writeFile(path, json, 'utf8')
    .then((success) => {
      count++;
      console.log('FILE WRITTEN! : ');
    })
    .catch((err) => {
        console.log(err.message);
    });

然后我继续尝试阅读它

var path = RNFS.DocumentDirectoryPath + '/test.json';

const cFile = RNFS.readFile(path, 'utf8');

遗憾的是,我只得到了“承诺”,但似乎无法直接访问数据。 我在控制台中得到了这种结果。

Promise {_40: 0, _65: 0, _55: null, _72: null}
_40:0
_55:"{"date":"2018-04-11T10:52:52+02:00","counter":0}"
_65:1
_72:null
__proto__:Object

我想访问日期字段,就像 cFile.date 一样

欢迎任何帮助,谢谢

【问题讨论】:

    标签: javascript json reactjs react-native fs


    【解决方案1】:

    这是您从 readFile 调用中获得的 Promise。你需要像这样调用'then':

    RNFS.readFile(path, 'utf8')
        .then((contents) => {
        // log the file contents
        console.log(contents);
      })
      .catch((err) => {
        console.log(err.message, err.code);
      });
    

    【讨论】:

      【解决方案2】:

      试试这个:

      let asset_content = null;
      try {
          await RNFetchBlob.fs.readFile(path, 'utf8')
            .then((data) => {
              asset_content = data;
              console.log("got data: ", data);
            })
            .catch((e) => {
              console.error("got error: ", e);
            })
        } catch (err) {
          console.log('ERROR:', err);
      }
      const assets = JSON.parse(asset_content);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-10-10
        • 1970-01-01
        • 2018-01-19
        • 2019-01-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多