使用另一个页面中的fetch call函数返回结果值,React native [英] Return the result value with fetch call function from another page, React native

查看:97
本文介绍了使用另一个页面中的fetch call函数返回结果值,React native的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从执行提取调用的react native中的另一个页面返回一个函数的结果。我使用如下方法。据我所知,这是因为异步调用。有没有一种特殊的方法可以在本机中实现这一点?

I need to return the result of a function from another page in react native which performing a fetch call. I use the method as follows. As I know this is because asynchronous call. Is there a special way to achieve this in react native ?

fetchcall.js

import address from '../actions/address'
const dashboard = {
  getvals(){

    return fetch(address.dashboardStats(),
    {method: "POST",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify( {...
      }),
    })
    .then((response) => response.json())
    .then((responseData) => {
      console.warn(responseData);
      return responseData;

    })
    .catch((error) => { console.warn(error); })
    .done();
    // return 'test_val'';
  }
}

export default dashboard;

dashboard.js

import dashboard from '../../services/dashboard';
class Dashboard extends Component {


  componentDidMount(){
      console.warn(dashboard.getvals());
  }

}

export default connect(mapStateToProps, bindAction)(Dashboard);

它将结果显示为未定义,但该提取调用有效并显示结果。有什么建议吗?

Its display the result as "undefined", but that fetch call works and it displays the result. Any suggestion?

推荐答案

fetchcall.js 中,您将返回一个Promise。此外,由于您在 .then()方法本身返回 responseData ,因此您不需要 .done()方法。

In fetchcall.js you are returning a Promise. Also since you are returning the responseData in the .then() method itself, you don't need the .done() method.

由于 getvals()是返回Promise,你需要在 .then()方法中访问它的值。

Since getvals() is returning a Promise, you need to access it's value in a .then() method.

总的来说,你的代码应该是这样的:

Overall, your code should be like this:

  function getvals(){
    return fetch('https://jsonplaceholder.typicode.com/posts',
    {
    	method: "GET",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
    })
    .then((response) => response.json())
    .then((responseData) => {
      console.log(responseData);
      return responseData;
    })
    .catch(error => console.warn(error));
  }
  
  getvals().then(response => console.log(response));

这篇关于使用另一个页面中的fetch call函数返回结果值,React native的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆