正如标题所说,我想使用 AsyncStorage 将两个值保存到本地存储中。 我的应用程序非常简单。 有两个按钮可以通过按下它们来增加每个数字。 它们被置于 setState 中。 我将它们保存到本地存储中,并希望在用户关闭/重新访问我的应用程序时使用它们。
我成功地让它适用于一个值,但不适用于另一个值,尽管我相信它们的结构与下面的代码相同。
import React, { useEffect, useState } from "react";
import { View, Text, StyleSheet, Button } from "react-native";
import AsyncStorage from "@react-native-async-storage/async-storage";
const Home = () => {
const [counter, setCounter] = useState(0);
const [counter2, setCounter2] = useState(0);
//For getting values that are saved into the local storage.
const get = async () => {
const values = await AsyncStorage.multiGet(["@count", "@count2"]);
values.forEach((value) => {
if (value[0] === "@count") {
const savedcount = parseInt(value[1]);
setCounter(savedcount);
console.log("rendering2");
}
if (value[0] === "@count2") {
const savedcount2 = parseInt(value[1]);
setCounter2(savedcount2);
console.log("rendering");
}
});
};
useEffect(() => {
get();
}, []);
const increment = async () => {
setCounter((pre) => pre + 1);
};
const increment2 = async () => {
setCounter2((pre) => pre + 1);
};
//For saving those states.
const saving = async () => {
await AsyncStorage.setItem("@count", counter.toString());
await AsyncStorage.setItem("@count2", counter2.toString());
};
useEffect(() => {
saving();
}, [counter, counter2]);
return (
<View style={styles.container}>
<Text style={styles.text}>{counter}</Text>
<Text style={styles.text}>{counter2}</Text>
<Button title="count up" onPress={increment} />
<Button title="count up2" onPress={increment2} />
</View>
);
};
const styles = StyleSheet.create({
container: {
justifyContent: "center",
alignItems: "center",
flex: 1,
},
text: {
fontSize: 50,
},
});
export default Home;
最后,
counter
被成功保存和使用,但 counter2
不是,即使它们的结构与我相信的相同。
我需要一些帮助。如果有人修复我的代码以使其正常工作,那就太好了。 提前谢谢你。