我正在尝试使用不同的函数,使用保存在变量中的一些信息来完成API Post。
为了在制作POST方法之前获得这些数据,我必须使用API POST获得一个Bearer Token,但这个请求需要一些时间。
我的屏幕上有一个按钮,我想用它来制作最终的API帖子,将信息保存在Firebase中并导航到下一个屏幕,但为此我需要我的代币持有者。我不知道如何制作我的第二个API Post,以便及时获得变量中的承载令牌,所以我可以以正确的方式制作我的API Post决赛。
也许有一种更简单的方法可以用Axios设置我的承载令牌,因为我必须在不同的屏幕上做几个API帖子,而这个令牌有一个过期时间。
我的代码的问题是,在我触摸按钮3次后,它就工作了,并且我可以导航到我的下一个屏幕(下一屏幕的名称在API Post最终版的响应中(。
我第一次触摸按钮时,会出现下一个错误:任何导航器都没有处理有效载荷为{"name":"}的操作"NAVIGATE"。
您需要传递要导航到的屏幕名称。
但在此之后,mi承载令牌被正确设置并出现在mi控制台中。
第二次触摸按钮时,我为使此调用异步而创建的函数正在正确执行,并将此消息发送到控制台:承诺已解决:LOG下一步-->API POST数据库中保存的LOG数据和API请求已完成
在此之后,承载令牌再次出现在我的控制台中,随后是最终API Post的响应,但它没有正确导航。
第三次我触摸按钮时,它正常工作,向控制台发送与上一步相同的信息,但导航到下一个屏幕。
我附上了我的代码,为了安全起见更改了一些信息。
import React, {useState, useContext, useEffect} from 'react';
import axios from 'axios';
import firestore from '@react-native-firebase/firestore';
import FormInput from '../../components/FormInput';
import {
View,
Text,
ScrollView,
FlatList,
TouchableOpacity,
Image,
TextInput,
Button
} from 'react-native';
import { COLORS, SIZES, FONTS, icons, image, functions, dummyData} from "../../constants"
import FormButton from '../../components/FormButton';
import { AuthContext } from '../../navigation/AuthProvider';
// Variables to set new values
let user_token = '';
let nextStep = '';
//let username = '';
const myFirstScreen = ( {navigation} ) => {
const { user} = useContext(AuthContext);
const [username, setUsername] = useState();
// const [user_token, setUserToken] = useState();
// const [nextStep, setNextStep] = useState();
const [isLoading, setIsLoading] = useState(false);
// Save User name and id in Firebase database
const submitUserdata = async () => {
firestore()
.collection('UserData')
.doc(user.uid)
.set ({
userId: user.uid,
userName: username,
})
.then ( () => {
console.log('User NAME and ID Added!')
})
.catch((error) => {
console.log(error)
});
};
function getCredentialsInfo() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve (getBearerToken())
}, 10)
})
}
async function setUserDataDB() {
const result = await getCredentialsInfo()
console.log('Promise Resolved: ')
console.log('Next step --> API POST')
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve (onSubmitFormHandler() )
}, 10)
})
};
async function callForButton() {
const result = await setUserDataDB()
console.log('Data saved in DB and API Request completed')
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve ( navigation.navigate(nextStep) )
}, 10)
})
}
//getCredentiales, client_id and client_secret wont be here in the future
const getBearerToken = () => {
const client_id = "xxxxxx";
const client_secret = "xxxxxxx";
axios.post('myurl.com',
{client_id,
client_secret})
.then(response => {
console.log(response.data);
//setUserToken(response.data.access_token);
user_token = response.data.access_token;
})
.catch((error) => {
console.log('error en Get Token ' + error);
});
}
// API Rest POST - User Name Validation -
const onSubmitFormHandler = (event) => {
axios.post("myurl.com/2",
{username},
{headers: {'Authorization': `Bearer ${user_token}`}})
.then(response => {
// If request es 200
console.log(response.data);
// setNextStep(response.data.next_action);
nextStep = response.data.next_action;
console.log(response.data.next_action)})
.catch((error) => {
console.log('Error en POST ' + error);
//setNextStep('myFirstScreen')
nextStep = 'actual screen';
});
};
return (
<View style={{
alignItems: 'center',
height: "100%",
width: "100%",
backgroundColor: COLORS.white
}}>
<View style={{
// marginTop: "10%",
// marginBottom: "10%",
alignItems: 'center'
}}>
<View style={{
backgroundColor: COLORS.lightGray1,
borderRadius: 40,
height: "85%",
width: "100%"
}}>
<View style={{
width: "100%",
paddingHorizontal: "8%",
paddingVertical: "10%"
}}>
{/* Username */}
<FormInput
labelValue = {username}
//onChangeText = {(userName) => username = userName}
onChangeText = {(userName) => setUsername (userName)}
placeholderText = "Username"
autoCapitalize = "none"
autoCorrect = {false}
/>
</View>
</View>
<FormButton buttonTitle='Save User Name'
//onPressIn ={() => {getToken()}}
onPress={() => {
// submitUserdata()
// onSubmitFormHandler()
// navigation.navigate(nextStep)
callForButton()
}}
disabled={isLoading}/>
</View>
</View>
);
}
export default myFirstScreen;
提前谢谢!欢迎提出任何建议。我不知道useState((钩子是否让某些东西以一种糟糕的方式工作。
瓦迪姆回答有效,我在下面的屏幕上遇到了问题,及时设置了用户名。
import React, { useContext, useState } from 'react';
import {
StyleSheet,
View,
Text,
Button,
} from 'react-native';
import { COLORS, SIZES, FONTS, icons, images} from "../../constants"
import FormInput from '../../components/FormInput';
import FormButton from '../../components/FormButton';
import { AuthContext } from '../../navigation/AuthProvider';
import firestore from '@react-native-firebase/firestore';
import {Login} from '../Login';
import axios from 'axios';
let user_token = '';
let nextStep = '';
let username = '';
const followingScreen = ( {navigation} ) => {
const { user } = useContext(AuthContext); // Funcionalidad del boton de logout
const [isLoading, setIsLoading] = useState(false);
//const [user_token, setUserToken] = useState();
//const [nextStep, setNextStep] = useState();
//const [username, setUsername] = useState('');
const [document_number, setDocumentNumber] = useState();
const [gender, setGender] = useState();
const [last_names, setLastNames] = useState();
const [birthdate, setBirthDate] = useState();
const [names, setNames] = useState();
const [order, setOrder] = useState();
// Bandera para validar que la data del usuario se guardo en Firebase
const [userDataSent, setUserDataSent] = useState(false);
const submitUserdata = async () => {
firestore()
.collection('UserData')
.doc(user.uid)
.update ({
//userId: user.uid,
//userName: username,
userDoc: document_number,
userGender: gender,
userLastname: last_names,
userDate: birthdate,
userFirstname: names,
userTramitnum: order
})
.then ( () => {
//setUserDataSent(true)
console.log('Se agrega nueva INFO al user ID!')
})
.catch((error) => {
console.log(error)
});
};
//Obtener el token de MiiiApp
const getBearerToken = () => {
//Data para credenciales
const client_id = "xxxxx";
const client_secret = "xxxx";
return axios.post('myurl.com',
{client_id,client_secret})
.then(response => {
console.log(response.data);
//setUserToken(response.data.access_token);
user_token = response.data.access_token;
})
.catch((error) => {
console.log('error en Get Token ' + error);
});
}
async function setUserDataDB() {
const result = await getBearerToken()
console.log('Promise Resolved Ya tengo mi token: ')
console.log('Next step --> Get user name')
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve ( getSpecUserData())
}, 10)
})
};
const getSpecUserData = () => {
function callUserData(documentSnapshot) {
return documentSnapshot.get('userName');
}
firestore()
.collection('UserData')
.doc(user.uid)
.get()
.then(
documentSnapshot => callUserData(documentSnapshot)
)
.then(callUserData => {
username = callUserData
//setUsername(callUserData)
console.log('This is my user that I have just gotten ' + username)
});
return username
};
async function getUserNameInfo() {
const result = await setUserDataDB()
console.log('Promise Resolved Ya tengo mi token y User Name: ' + username)
console.log('Next step --> API Call')
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve ( onSubmitFormHandler(), submitUserdata())
}, 10)
})
};
async function callForButton() {
const result = await getUserNameInfo()
console.log('API Request completed')
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve ( navigation.navigate(nextStep) )
}, 10)
})
}
// API Rest POST - Personal Data -
const onSubmitFormHandler = async (event) => {
setIsLoading(true);
return axios.post("myurl2.com",
{username,
document_number,
gender,
names,
last_names,
birthdate,
order
},
{headers: {'Authorization': `Bearer ${user_token}`}}
)
.then(response => {
// If request es 200
console.log(response.data);
setIsLoading(false);
//setNextStep(response.data.next_action);
nextStep = response.data.next_action;
//setUsername('');
setDocumentNumber('');
setGender('');
setLastNames('');
setBirthDate('');
setNames('');
setOrder('');
})
.catch((error) => {
console.log(error.toJSON());
setIsLoading(false);
//setNextStep('followingScreen')
nextStep = 'followingScreen';
});
};
return (
<View style={{
alignItems: 'center',
height: "100%",
width: "100%",
backgroundColor: COLORS.white
}}>
<View style={{
// marginTop: "10%",
// marginBottom: "10%",
alignItems: 'center'
}}>
<View style={{
backgroundColor: COLORS.lightGray1,
borderRadius: 40,
height: "85%",
width: "100%"
}}>
<View style={{
width: "100%",
paddingHorizontal: "8%",
paddingVertical: "10%"
}}>
{/* Username */}
{/* <FormInput
labelValue = {username}
onChangeText = {(userName) => setUsername (userName)}
placeholderText = "Username"
autoCapitalize = "none"
autoCorrect = {false}
/> */}
{/* Numero de Documento */}
<FormInput
labelValue = {document_number}
onChangeText = {(userDoc) => setDocumentNumber(userDoc)}
placeholderText = "Numero de Documento"
keyboardType = "numeric"
/>
{/* Genero */}
<FormInput
labelValue = {gender}
onChangeText = {(userGen) => setGender(userGen)}
placeholderText = "Genero"
/>
{/* Nombre */}
<FormInput
labelValue = {names}
onChangeText = {(userFirst) => setNames (userFirst)}
placeholderText = "Nombre"
autoCorrect = {false}
/>
{/* Apellido */}
<FormInput
labelValue = {last_names}
onChangeText = {(userLast) => setLastNames (userLast)}
placeholderText = "Apellido"
autoCorrect = {false}
/>
{/* Fecha de Nacimiento*/}
<FormInput
labelValue = {birthdate}
onChangeText = {(userBirth) => setBirthDate (userBirth)}
placeholderText = "Fecha de Nacimiento"
keyboardType = "numeric"
/>
{/* Numero de Tramite DNI */}
<FormInput
labelValue = {order}
onChangeText = {(userTramit) => setOrder (userTramit)}
placeholderText = "Numero de Tramite DNI"
keyboardType = "numeric"
/>
</View>
</View>
<FormButton buttonTitle='Save User Data'
onPress={() => {
callForButton()
}}
disabled={isLoading}
/>
</View>
</View>
);
}
export default followingScreen;
Expand snippet
Share
Edit
Delete (1)
Flag
answe
我认为问题是您正在等待getBearerToken
,但它似乎没有返回任何内容,因此等待立即得到解决。尝试在axios之前添加return
,以在此方法中返回axios promise。就像这个return axios.post('myurl.com'...
。
也可以将await getCredentialsInfo()
更改为await getBearerToken()