如何在React Native中从函数返回值

时间:2018-09-01 09:26:27

标签: javascript reactjs react-native react-router

此函数从我正在使用的API返回令牌数据。

// api.js
var token="";
    const tokenAl= {
  tokenner: function(){
    fetch("myurl/api/token", {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json-patch+json"
      },
      body: JSON.stringify({
        // here is not important
      })
    })
      .then(response => response.json())
      .then(responseJson => {
       token= responseJson.result.token;
        console.warn(token) // it's ok. I got the token.
      })
      .catch(error => console.warn(error));    
       // this.props.navigation.navigate("Customer"); // Customer sayfasına gidiş.
  },
}

export default tokenner;

一切都很好。现在,如何在Login-Form.js文件中使用此令牌值?

1 个答案:

答案 0 :(得分:1)

首先是export default tokenAl.tokenner

要在另一个文件中使用它,只需将其添加到Login-Form.js的顶部

import tokenner from './api.js'; //assuming it's located in the same directory

您将需要修改tokenner功能,以便检索令牌。兑现承诺。

tokenner: function(){
    return fetch("myurl/api/token", {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json-patch+json"
      },
      body: JSON.stringify({
        // here is not important
      })
    })
      .then(response => response.json());
  }

然后在您的LoginFormComponent中

import React, { Component } from "react";
import tokenner from "./api";

export default class LoginFormComponent extends Component {
  constructor() {
    super();
    this.state = { token: null };
  }

  componentWillMount() {
    tokenner()
      .then(responseJson => {
        const token = responseJson.result.token;
        console.warn(token); // it's ok. I got the token.
        this.setState({ token });
      })
      .catch(error => console.warn(error));
  }
  render() {
    const { token } = this.state;
    return <div>{token}</div>;
  }
}

Working example here