當用戶要求登錄時我創建 reactjs 應用程式我發送三個請求
getToken();
createLogWithToken();
createRequestwithLog();
每個函式都依賴于前一個函式這是我的代碼
getToken = async (){
axios.post('getToken')
.then(response => {
this.setState({ token: response.data.token });
})
}
createLogWithToken = async (){
axios.post('createLogWithToken',{token:this.state.token})
.then(response => {
this.setState({ log_id: response.data.log_id });
})
}
createRequestwithLog = async (){
axios.post('createRequestwithLog',{token:this.state.token, log_id: this.state.log_id})
.then(response => {
this.setState({ request_id: response.data.request_id });
})
}
onPress = async () =>{
await this.getToken();
await this.createLogWithToken();
await this.createRequestwithLog();
}
我在第二個命令上收到錯誤,因為所需的引數為空我如何呼叫然后等待直到 setstate 完成
編輯>>我將我的代碼更改為
getToken = async (){
await axios.post('getToken')
.then(response => {
this.setState({ token: response.data.token });
return (response.data.token);
})
}
createLogWithToken = async (token){
await axios.post('createLogWithToken',{token})
.then(response => {
this.setState({ log_id: response.data.log_id });
return response.data.log_id;
})
}
createRequestwithLog = async (token, log_id){
await axios.post('createRequestwithLog',{token, log_id})
.then(response => {
this.setState({ request_id: response.data.request_id });
return response.data.request_id;
})
}
onPress = async () =>{
let token = await this.getToken();
let log = await this.createLogWithToken(token);
let request = await this.createRequestwithLog(token,log);
}
但我仍然收到令牌未定義的錯誤
uj5u.com熱心網友回復:
幾件事:
您正在等待的功能不是“可等待的”。你需要回傳一個承諾。
您可以像這樣直接等待您的 axios 呼叫
const token = await axios.post...setState 不是同步的。您不知道它是否在您呼叫下一個端點時定義。您應該將它們設定為普通變數。如果您還需要它們作為狀態,您也可以這樣做,但看起來沒有必要
uj5u.com熱心網友回復:
請參閱如何構建嵌套的 Promise
fetch(url)
.then(function(response) {
return response.json()
})
.then(function(data) {
// do stuff with `data`, call second `fetch`
return fetch(data.anotherUrl)
})
.then(function(response) {
return response.json();
})
.then(function(data) {
// do stuff with `data`
})
.catch(function(error) {
console.log('Requestfailed', error)
});
uj5u.com熱心網友回復:
getToken = async () {
const token = (await axios.post('getToken')).data.token;
this.setState({ token });
return token;
}
createLogWithToken = async (token) {
const logId = (await axios.post('createLogWithToken',{ token })).data.log_id;
this.setState({ log_id: logId });
return logId;
}
createRequestwithLog = async (token, logId) {
const requestId = (await axios.post('createRequestwithLog',{ token, log_id: logId })).data.request_id;
this.setState({ request_id: requestId});
}
onPress = async () => {
const token = await this.getToken();
const logId = await this.createLogWithToken(token);
this.createRequestwithLog(token, logId);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/494476.html
標籤:javascript 反应 异步
