【问题标题】:Adding data to existing JSON file with react native使用本机反应将数据添加到现有 JSON 文件
【发布时间】:2019-04-10 12:16:27
【问题描述】:

我正在尝试从文本输入向现有 JSON 文件添加一些新数据。 我使用 React Native 并将一些数据存储在名为 PartyInfo.json 的 JSON 文件中,当我填写表单时,我希望将数据传递并存储在 PartyInfo.json 文件中。

const PartyInfo = require('../PartyInfo.json');

let party = {
        name: this.state.name,
        info: this.state.info,
        date: this.state.date,
        price: this.state.price,
    };
    let data = JSON.stringify(party);
    PartyInfo.writeFile('PartyInfo.json', data);

我已经尝试遵循类似问题的一些答案,但没有任何效果...... 提前致谢。

【问题讨论】:

标签: javascript json react-native


【解决方案1】:

你只需要安装 npm i react-native-fs 使用 npm i react-native-fs 并使用以下代码更新您的文件

 var RNFS = require('react-native-fs');

    var filePath = RNFS.DocumentDirectoryPath + '/YOUR_FILE_NAME';

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

【讨论】:

  • 我刚刚尝试过,它向我显示了“成功”消息,但输入没有附加到我的 JSON 文件中......有什么想法吗?
  • 这不起作用。
猜你喜欢
  • 2018-06-19
  • 1970-01-01
  • 1970-01-01
  • 2018-09-14
  • 2022-01-13
  • 1970-01-01
  • 2013-10-02
  • 1970-01-01
  • 2022-01-22
相关资源
最近更新 更多