简体   繁体   English

如何从反应本机中的函数返回值

[英]How to return a value from a function in react native

This function returns the token data from the API I am using.此函数从我使用的 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;

Everything is okay.一切正常。 Now, how do I use this token value in the Login-Form.js file?现在,我如何在 Login-Form.js 文件中使用这个令牌值?

First of all it's export default tokenAl.tokenner .首先它是export default tokenAl.tokenner

To use it in another file, simply add this at the top of your Login-Form.js要在另一个文件中使用它,只需将它添加到 Login-Form.js 的顶部

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

You'll need to modify your tokenner function so that you can retrieve the token.您需要修改您的 tokenner 函数,以便您可以检索令牌。 Return a promise.返回一个承诺。

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());
  }

Then in your LoginFormComponent然后在您的 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这里的工作示例

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

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