gpt4 book ai didi

javascript - React-Native:保存用户偏好

转载 作者:行者123 更新时间:2023-12-03 12:26:32 25 4
gpt4 key购买 nike

原生开发者,

我真的搜索了很多,但找不到任何适合我需要的东西。

我是新来的 react 原生并有一个问题。
我想知道如何保存我的应用程序的用户偏好。

例如,我在我的屏幕上显示一个可关闭的徽章 -> 用户将其关闭 -> 我如何保存此决定,以便徽章不会再次出现在每次开始时?

我考虑编写一个 .json 文件,其中定义了所有首选项并在每次开始时读取它。

这是实现它的常用方法还是有其他解决方案。

非常感谢

最佳答案

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
}
}

  • 已弃用的文档:https://reactnative.dev/docs/asyncstorage
  • 异步存储文档:https://react-native-async-storage.github.io/async-storage/docs/install/
  • 考虑其他选项:https://reactnative.directory/?search=storage

  • 旧答案
    有很多选项,但您可以使用的最常见的是内置的 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
    或者您可以重新考虑 3rd 方库,例如:
    https://github.com/kevinresol/react-native-default-preference
    https://github.com/mCodex/react-native-sensitive-info

    关于javascript - React-Native:保存用户偏好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51772969/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com