React Native:将数据保存到AsyncStorage



你好,我正试图在登录应用程序后将数据保存到AsyncStorage中,但我不太确定在哪里实现AsyncStorage语法?异步存储文档我知道我必须以某种方式将对象转换为字符串(JSON.stringify(,然后在得到响应的地方添加代码润滑油。

const LoginForm = ({navigation}) => {

const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [isLoggedIn, setIsLoggedIn] = useState(false);

async function handleSubmit(){
const headers = await getUserToken() //'profile'
//console.log(headers, 'getusertoken')
const data = { email, password };
console.log(data, 'this is dataa')

const requestOptions = {
method: "POST",
headers: { "Content-Type": "application/json",
ACCEPT: 'application/json', },
body: JSON.stringify(data)
};

fetch("API_HERE/auth/sign_in", requestOptions)
.then(response => console.log(headers.response)
//console.log(response.headers, 'response'),
)

//.then(res => console.log(res));
//setEmail(true)
//setPassword(true)
setIsLoggedIn(true)
if(setIsLoggedIn){
return navigation.navigate('ProfileLanding')  
}  
}


return (
<SafeAreaView style={styles.container}>
<ScrollView>
<View style={styles.loginBar}>
<Text style={styles.loginTitle}>Login to my app</Text>
<View className="login-form">
<TextInput
className="login-info"
style={styles.input}
id="id"
onChangeText={(text) => setEmail(text)}
type="text"
placeholder="example@gmail.com"
value={email}/>
<TextInput
className="login-info"
style={styles.input}
id="id"
onChangeText={(text) => setPassword(text)}
type="text"
placeholder="password"
value={password}
secureTextEntry/>
</View>
<View style={styles.btnContainer}>


<TouchableOpacity style={styles.userBtn}>
<Text style={styles.userText} 
onPress={() =>
handleSubmit()}>Login</Text>
</TouchableOpacity>
<TouchableOpacity  
style={styles.userBtn}
onPress={()=> alert('login works!')}>
<Text style={styles.userText}>Sign Up</Text>
</TouchableOpacity>

</View>
{isLoggedIn ? (
<Text>You are Logged IN!</Text>
) : (
<Text>Come inside!</Text>
)}

</View>
</ScrollView>
</SafeAreaView>

);
}

在handleSubmit函数中,获取响应后,将数据存储在AsyncStorage中,如下所示-

AsyncStorage.setItem("loginData", JSON.stringify(data));

然后在某个异步函数(您可以在useEffect中调用该函数(中从异步存储中获取数据。

let data = await AsyncStorage.getItem("loginData");
const LoginForm = ({navigation}) => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [isLoggedIn, setIsLoggedIn] = useState(false);
async function handleSubmit(email, password) {
const data = {email, password};
console.log(data, 'this is dataa');
const requestOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
ACCEPT: 'application/json',
},
body: JSON.stringify(data),
};
fetch('API_HERE/auth/sign_in', requestOptions).then(async response => {
//replace it with respect to your API token
if (response.token) {
await AsyncStorage.setItem('userToken', response.token); 
setIsLoggedIn(true);
if (setIsLoggedIn) {
navigation.navigate('ProfileLanding');
}
}
});
}
return (
<SafeAreaView style={styles.container}>
<ScrollView>
<View style={styles.loginBar}>
<Text style={styles.loginTitle}>Login to my app</Text>
<View className="login-form">
<TextInput
className="login-info"
style={styles.input}
id="id"
onChangeText={text => setEmail(text)}
type="text"
placeholder="example@gmail.com"
value={email}
/>
<TextInput
className="login-info"
style={styles.input}
id="id"
onChangeText={text => setPassword(text)}
type="text"
placeholder="password"
value={password}
secureTextEntry
/>
</View>
<View style={styles.btnContainer}>
<TouchableOpacity style={styles.userBtn}>
<Text
style={styles.userText}
onPress={() => handleSubmit(email, password)}>
Login
</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.userBtn}
onPress={() => alert('login works!')}>
<Text style={styles.userText}>Sign Up</Text>
</TouchableOpacity>
</View>
{isLoggedIn ? (
<Text>You are Logged IN!</Text>
) : (
<Text>Come inside!</Text>
)}
</View>
</ScrollView>
</SafeAreaView>
);

};

假设您需要在成功登录后保存身份验证令牌。

function saveUserToken(token) {
try {
await AsyncStorage.setItem("userToken", token.toString());
} catch (error) {
// Error saving data
}
}
async function handleSubmit() {
const headers = await getUserToken(); //'profile'
//console.log(headers, 'getusertoken')
const data = { email, password };
console.log(data, "this is dataa");
const requestOptions = {
method: "POST",
headers: {
"Content-Type": "application/json",
ACCEPT: "application/json",
},
body: JSON.stringify(data),
};
fetch("API_HERE/auth/sign_in", requestOptions).then(
(response) => {
//Mocked userToken access - replace with API data structure
const userToken = response.data.userToken;
// Save token on user device
saveUserToken(userToken);
}
);
//.then(res => console.log(res));
//setEmail(true)
//setPassword(true)
setIsLoggedIn(true);
if (setIsLoggedIn) {
return navigation.navigate("ProfileLanding");
}
}


最新更新