我有一个用于输入电子邮件和密码的字段,当我单击登录按钮时,我正在调用一种从后端获取用户的方法,如果响应成功,则应该可以导航至下一页。我怎么做?我有一个可以在Postman中正常工作的api,如何将api与UI连接并存储响应数据?在下面的代码中,我附加了我在代码中使用的api的响应图像
import React from 'react';
import { StyleSheet, Text, View, Button, TextInput } from 'react-native';
import PresentationalComponent from './PresentationalComponent'
export default class App extends React.Component {
constructor(){
super();
this.state = {
email: '',
password: '',
result: false,
}
}
updateState = () => {
this.setState({ myState: 'The state is updated' })
}
_userLogin() {
var email = this.state.username;
var password = this.state.password;
if (email && password) { // if validation fails, value will be null
fetch("http://localhost:5000/api/login", {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: email,
password: password,
})
})
.then((response) => response.json())
.then((responseData) => {
console.log(responseData);
AlertIOS.alert(
"Login Success!",
"Click the button to get a Chuck Norris quote!"
),
this._onValueChange(STORAGE_KEY, responseData.id_token)
})
.done();
renderResults();
}
}
renderResults = () => {
if(responseData){
this.setState({
result: true
})
}
}
handleEmail = (text) => {
this.setState({ email: text })
}
handlePassword = (text) => {
this.setState({ password: text })
}
render() {
return (
<View>
{this.state.result ?
<PresentationalComponent/>
:
<View>
<TextInput
underlineColorAndroid = "transparent"
placeholder = "Email"
placeholderTextColor = "#9a73ef"
autoCapitalize = "none"
onChangeText = {this.handleEmail}
/>
<TextInput
underlineColorAndroid = "transparent"
placeholder = "Password"
placeholderTextColor = "#9a73ef"
autoCapitalize = "none"
onChangeText = {this.handlePassword}
/>
<Button
onPress={this._userLogin}
title="Learn More"
color="#841584"
accessibilityLabel="Learn more about this purple button"
/>
</View>
}
</View>
);
}
}
答案 0 :(得分:0)
如果您使用反应导航,这很简单
if (response.status == "200")
{
this.props.navigation.navigate(" ") //Add the page name in quote
}
答案 1 :(得分:0)
我发现this article可能会对您有所帮助。
建议使用两个令牌-查看当前的API响应,我看不到任何令牌-重要的是要了解令牌和ID是两个不同的概念-您可能希望在登录过程中生成令牌。这些字符串可让服务器确保客户端已通过身份验证。
建议的实现,从开始到文章(略有简化):
Authorization
例如,用户在一天后打开该应用程序时,应从步骤2开始继续获取新的访问令牌。
用户注销后,应用程序应请求撤销两个令牌,以使其不再可用。