【问题标题】:How to return a value from a function in react native如何在本机反应中从函数返回值
【发布时间】:2019-02-07 03:42:15
【问题描述】:

此函数从我正在使用的 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 文件中使用这个令牌值?

【问题讨论】:

  • 您需要在组件内部使用state,并在您提取令牌的then方法回调中调用组件的状态更新器方法。
  • 我试过了,但我做不到。你能为我写信吗?

标签: javascript reactjs react-native react-router


【解决方案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

【讨论】:

  • 感谢你,我的朋友。谢谢你。问题解决了。
  • 我想使用我在每个页面上获得的令牌。我的意思是,我打开一次令牌就足够了,我会用它来进行各种查询。我该怎么做?
  • 最简单的方法是使用我们所说的“商店”。将其视为一项服务,您可以轻松地将其与每个组件一起使用。我建议你查看 mobx/mobx-react (mobx.js.org)。但是,如果安装起来太麻烦(可能取决于您的设置),只需调用一次 tokenner 并将令牌存储为 cookie 或将其放入本地存储中,然后您可以从任何组件中检索它。 (cookies:developer.mozilla.org/en-US/docs/Web/API/Document/cookie,本地存储:developer.mozilla.org/en-US/docs/Web/API/Window/localStorage)。
  • 如果您有兴趣,我会使用存储来检索我的令牌,并使用该存储将密钥保存为 cookie。因此,当页面刷新时,我总是检查密钥是否存在于 cookie 中,如果不存在,则执行 API 请求来获取 cookie(然后将其存储在 cookie 中以备将来使用)。
猜你喜欢
  • 2021-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多