首页 > 解决方案 > React axios:如何在继续代码之前等待数据

问题描述

所以我必须调用 API 来获取令牌,然后使用响应调用另一个 API 来登录应用程序。

使用同样的代码,render() 要求一个 ';' 在它之后,console.log 在返回令牌之前返回消息......

这是我的代码:

APITOKEN.js:
import axios from 'axios';
import React,{Component} from 'react';
import ReactDOM from "react-dom";

apitoken =  async () =>{
    this.isLoading = true;
try {
    await axios.post('http://192.168.100.60:94/jderest/tokenrequest', {
        username: 'JDE',
        password: 'JDE'
      })
          .then(response => {
           console.log('returned data from api'+response.data.userInfo.token);
            this.userdetails = response.data.userInfo.token;
            this.isLoading = false;
           })
           .catch(error => {
                console.log(error);
                this.error = error
            })
 } catch (e) {
            console.log('ERROR', e);
           this.isLoading = false;
        };
    };
   export default apitoken;   

Login.js

const handleLogin = (credentials,setSubmitting) =>{
    handleMessage(null);

    this.apitoken();
     apitoken =  async () =>{
            await this.props.Apitoken.apitoken();
   } 
    render () {
       const { isLoading, userDetails, error } = this.props.Apitoken
            return (<View>
            {(!!isLoading)?<Text>{userDetails}</Text>:<Text>Loading</Text>}
            </View>)
    };
    console.log('jul222222222');
};

标签: reactjsapiasynchronousasync-awaitaxios

解决方案


推荐阅读