React-Native:保存用户偏好设置

19

本地开发人员,

我确实做了很多搜索但是找不到符合我的需求的内容。

我是react native的新手,有一个问题想请教。我想知道如何保存应用的用户偏好设置。

比如,我在屏幕上显示了一个可关闭的徽章 -> 用户关闭了它 -> 我该如何保存这个决定,以便徽章不会在每次启动时都出现?

我考虑过编写一个.json文件来定义所有的偏好设置,并在每次启动时读取它。

这是实现它的常见方式,还是有其他解决方案呢?

非常感谢。


5
您可以使用 AsyncStorage - Pritish Vaidya
https://facebook.github.io/react-native/docs/asyncstorage.html - Derek 朕會功夫
但需要注意的是,在最近版本的React Native中,当开启远程调试(Android)时,使用AsyncStorage会导致应用程序挂起。请阅读此问题https://github.com/facebook/react-native/issues/15476。 - I Putu Yoga Permana
1个回答

24

2022年2月更新的答案

React Native已正式弃用内置的 AsyncStorage,最新的解决方案是安装其社区包。

# Install via NPM
npm install --save @react-native-async-storage/async-storage

# ...or install via YARN
yarn add @react-native-async-storage/async-storage

# ...or install via EXPO
expo install @react-native-async-storage/async-storage

实现代码如下

import AsyncStorage from '@react-native-async-storage/async-storage';

const storeKey = '@storage_Key'
const storeData = async (value) => {
  try {
    await AsyncStorage.setItem(storeKey, value)
  } catch (e) {
    // saving error
  }
}


const getData = async () => {
  try {
    const value = await AsyncStorage.getItem(storeKey)
    if(value !== null) {
      // value previously stored
    }
  } catch(e) {
    // error reading value
  }
}

旧答案

有很多选择,但最常见的是使用React Native内置的AsyncStorage

示例代码

import { AsyncStorage } from "react-native";
const storeKey = 'myPreference';
storeData = async () => {
  try {
    await AsyncStorage.setItem(storeKey, 'I like to save it.');
  } catch (error) {
    // Error saving data
  }
}

retrieveData = async () => {
  try {
    const value = await AsyncStorage.getItem(storeKey);
    if (value !== null) {
      // We have data!!
      console.log(value);
    }
   } catch (error) {
     // Error retrieving data
   }
}

阅读更多内容,请访问https://facebook.github.io/react-native/docs/asyncstorage.html

或者您可以重新考虑使用第三方库,例如:

https://github.com/kevinresol/react-native-default-preference

https://github.com/mCodex/react-native-sensitive-info


“TASKS”这个关键字是从哪里来的?它似乎与“@MySuperStore:key”无关。虽然我不熟悉“@MySuperStore:key”语法。 - kojow7
啊,我的错,应该是相同的键。我更新了答案以获得更好的一致性。谢谢你指出来! - I Putu Yoga Permana
1
React Native内置的AsyncStorage现已被官方文档弃用,但社区分支@react-native-async-storage/async-storage得到了良好的支持。 - faraza

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接