无法从异步存储中检索密钥反应本机
can't retrieve key from async storage react native
我正在尝试使用记住我的切换开关将用户电子邮件存储在异步存储中。我不确定为什么我通过 getRememberedUser 调用检索“null”?我究竟做错了什么?这是 React Native,我也有一个 redux store(这里没有真正使用),但不确定这是否重要。谢谢!
const [userEmail, setuserEmail] = useState("");
const [rememberMe, setrememberMe] = useState(false);
const rememberUser = async () => {
try {
await AsyncStorage.setItem("userEmail", userEmail);
console.log("stored");
} catch (error) {
// Error saving data
}
};
const forgetUser = async () => {
try {
await AsyncStorage.removeItem("userEmail");
console.log("forgotten");
} catch (error) {
// Error removing
}
};
const getRememberedUser = async () => {
try {
const value = await AsyncStorage.getItem("userEmail");
console.log(value)
if (value !== null) {
// We have username!!
setuserEmail(value);
}
} catch (error) {
// Error retrieving data
}
};
<Input
id="email"
label="E-Mail"
keyboardType="email-address"
required
email
autoCapitalize="none"
errorText="Please enter a valid email address."
onInputChange={inputChangeHandler}
initialValue={userEmail}
/>
<Switch
value={rememberMe}
onValueChange={(value) => toggleRememberMe(value)}
/>
<Text>Remember Me</Text>
<Button
title="get uersname"
onPress={() => {
getRememberedUser();
}}
></Button>
保存时需要字符串化,
await AsyncStorage.setItem("userEmail", JSON.stringify(userEmail));
并在检索时解析
const value = await AsyncStorage.getItem("userEmail");
const userEmail = JSON.parse(value);
我正在尝试使用记住我的切换开关将用户电子邮件存储在异步存储中。我不确定为什么我通过 getRememberedUser 调用检索“null”?我究竟做错了什么?这是 React Native,我也有一个 redux store(这里没有真正使用),但不确定这是否重要。谢谢!
const [userEmail, setuserEmail] = useState("");
const [rememberMe, setrememberMe] = useState(false);
const rememberUser = async () => {
try {
await AsyncStorage.setItem("userEmail", userEmail);
console.log("stored");
} catch (error) {
// Error saving data
}
};
const forgetUser = async () => {
try {
await AsyncStorage.removeItem("userEmail");
console.log("forgotten");
} catch (error) {
// Error removing
}
};
const getRememberedUser = async () => {
try {
const value = await AsyncStorage.getItem("userEmail");
console.log(value)
if (value !== null) {
// We have username!!
setuserEmail(value);
}
} catch (error) {
// Error retrieving data
}
};
<Input
id="email"
label="E-Mail"
keyboardType="email-address"
required
email
autoCapitalize="none"
errorText="Please enter a valid email address."
onInputChange={inputChangeHandler}
initialValue={userEmail}
/>
<Switch
value={rememberMe}
onValueChange={(value) => toggleRememberMe(value)}
/>
<Text>Remember Me</Text>
<Button
title="get uersname"
onPress={() => {
getRememberedUser();
}}
></Button>
保存时需要字符串化,
await AsyncStorage.setItem("userEmail", JSON.stringify(userEmail));
并在检索时解析
const value = await AsyncStorage.getItem("userEmail");
const userEmail = JSON.parse(value);