简体   繁体   English

如何使用 React Native 持久化单个状态值

[英]How to persist individual state values using React Native

I have a button in my react native app which toggles a state value from true to false:我的 React Native 应用程序中有一个按钮,可将状态值从 true 切换为 false:

const [isLearned, setIsLearned] = useState(false);

addRemoveCardToLearned = () => {
  setIsLearned(!isLearned);
};

This button can be used on multiple cards within the app, and so each card will always have it's own state for isLearned , either true or false.此按钮可用于应用程序内的多张卡片,因此每张卡片将始终具有自己的isLearned状态,无论是 true 还是 false。 What I need to do is persist the state value of each individual card after page refresh.我需要做的是在页面刷新后保留每张卡片的状态值。 I have tried using AsyncStorage with the useEffect hook:我曾尝试将 AsyncStorage 与 useEffect 挂钩:

useEffect(() => {
  AsyncStorage.setItem('isLearned', JSON.stringify(isLearned));
}, [isLearned]);

useEffect(() => {
  const storeIsLearned = Boolean(AsyncStorage.getItem('isLearned'));
  setIsLearned(storeIsLearned);
}, []);

But what this does is change all cards state value at once.但这所做的是一次更改所有卡片状态值。 I also tried inserting a getter function within the code for my button:我还尝试在按钮的代码中插入一个 getter 函数:

addRemoveCardToLearned = () => {
  setIsLearned(!isLearned);

  AsyncStorage.getItem('isLearned').then((isLearned) => {
    console.log(isLearned);
  });
};

But this just records every entry as true .但这只是将每个条目记录为true

Since each card will have a different state value is there a way to persist each of them individually?由于每张卡都有不同的状态值,有没有办法单独保留每张卡?

Async storage is global that is why it updates all the cards because all the cards are referring to a single isLearned key valye pair in the Async storage.异步存储是全局的,这就是它更新所有卡片的原因,因为所有卡片都引用异步存储中的单个 isLearned 键值对。 Adding a unique code to each async storage while saving the state can solve the problem.在保存状态的同时为每个异步存储添加唯一的代码可以解决问题。

<FirstComponent uniqueCode='001' />
<FirstComponent uniqueCode='002' />

prefix the uniqueCode prop to the key name while saving the data to Async Storage, and also while reading from the Async storage.在将数据保存到异步存储以及从异步存储读取数据时,将 uniqueCode 属性添加到键名前。

useEffect(() => {   AsyncStorage.setItem(`${props.uniqueCode}_isLearned`, 
JSON.stringify(isLearned)); }, [isLearned]);

useEffect(() => {   const storeIsLearned = 
Boolean(AsyncStorage.getItem(`${props.uniqueCode}_isLearned`));   
setIsLearned(storeIsLearned); }, []);

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

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