简体   繁体   English

在 React Native 中写入/编辑/覆盖 json 文件

[英]write/edit/overwrite a json file in react native

I know how to read the json file just by importing it我知道如何通过导入来读取 json 文件

import file from './config/data.json'; console.log(file); . .

But is there an easy way to write or edit on it.但是有没有一种简单的方法来编写或编辑它。

Use AsyncStorage for saving local settings:使用 AsyncStorage 保存本地设置:

The following is to set your settings in your code (This example is for some Switch下面是在你的代码中设置你的设置(这个例子是针对一些 Switch

async setSettings() {
  try {
    var obj = {};
    var settings = await AsyncStorage.getItem('settings');
    settings = JSON.parse(result);
    Object.assign(obj, settings);
    this.setState(obj);
  }
  catch(e) { }
  finally { }
}

The following is to change your settings in your code以下是更改代码中的设置

switchChanged(field, value) {
  var obj = {};
  obj[field] = value;
  AsyncStorage.getItem('settings').then(function(strResult) {
    var result = JSON.parse(strResult) || {};
    Object.assign(result, obj);
    AsyncStorage.setItem('settings', JSON.stringify(result));
  });
  this.setState(obj);
}

And finally the call at the render method最后调用 render 方法

<Switch
  onValueChange={(value) => this.switchChanged('reminders', value)}
  value={this.state.reminders} />

Hope it can help you :)希望它可以帮助你:)

If you absolutely want to read/write files you could use react-native-fs .如果你绝对想读/写文件,你可以使用react-native-fs

If you want to persist application specific settings I would recommend using AsyncStorage .如果您想保留特定于应用程序的设置,我建议使用AsyncStorage

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM