简体   繁体   English

如何在React Native中将异步功能的返回分配给变量

[英]How to assign the return of an async funtion to a variable in React Native

I try to find my way around in JavaScript and the React Native Framework: 我尝试在JavaScript和React Native Framework中找到解决方法:

Basically what I am trying is to speak with an API via fetch, so I set up an AsyncFunction: 基本上,我正在尝试通过获取与API通讯,因此我设置了AsyncFunction:

class MyComponent extends React.Component {
     async getToken(client_id, client_key, username, password) {
        try {
        let response = await fetch('https://expample.com/o/token/', {
            method: 'POST',
            body: JSON.stringify({
              client_id: client_id,
              client_secret: client_key,
              grant_type: 'password',
              username: username,
              password: password,
            })
          });
          let responseJson = await response.json();
          return responseJson.access_token;
        } catch(error) {
          console.error(error)
        }
      }
...
}

But now I have no idea how to call this function. 但是现在我不知道如何调用该函数。

var token = getToken.token

just gives a syntax error and 只是给出语法错误,

'token': getToken.token

also doesn't do the trick. 也没有办法。

You can assign the response to the component's state like so: 您可以像这样将响应分配给组件的状态:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { token: null, };
  }

  async getToken(client_id, client_key, username, password) {
    try {
    let response = await fetch('https://example.com/o/token/', {
        method: 'POST',
        body: JSON.stringify({
          client_id: client_id,
          client_secret: client_key,
          grant_type: 'password',
          username: username,
          password: password,
        })
      });
      let responseJson = await response.json();
      this.setState({ access_token: responseJson.access_token });
    } catch(error) {
      console.error(error)
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM