简体   繁体   English

使用 fetch 调用函数从另一个页面返回结果值,React native

[英]Return the result value with fetch call function from another page, React native

I need to return the result of a function from another page in react native which performing a fetch call.我需要从执行 fetch 调用的 react native 中的另一个页面返回函数的结果。 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 ?有没有一种特殊的方法可以在 react native 中实现这一点?

fetchcall.js获取调用.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仪表板.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.它将结果显示为“未定义”,但该 fetch 调用有效并显示结果。 Any suggestion?有什么建议吗?

In fetchcall.js you are returning a Promise.fetchcall.js 中,您将返回一个 Promise。 Also since you are returning the responseData in the .then() method itself, you don't need the .done() method.此外,由于您在.then()方法本身中返回responseData ,因此您不需要.done()方法。

Since getvals() is returning a Promise, you need to access it's value in a .then() method.由于getvals()返回一个 Promise,您需要在.then()方法中访问它的值。

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

The best architectural pattern, I think, is to use a callback function, usually by writing in as an anonymous function.我认为最好的架构模式是使用回调函数,通常是作为匿名函数写入。

///Component.js
my_service.login((data=>{
  this.setState({body: data.body});
}));

////Service.js
export  const login = function (cb){
  fetch('http://myapi.com/103?_format=hal_json')
    .then((response) =>{
      return response.json();
    })
    .then((data) =>{
      cb(data);
    });
}

I am still a junior developer, but use this pattern frequently.我仍然是初级开发人员,但经常使用这种模式。 If someone has a reason for a different approach, I would love to hear it.如果有人有理由采用不同的方法,我很乐意听到。

fetch always return a Promise doesn't matter what you are returning. fetch 总是返回一个 Promise 与您返回的内容无关。 so you can return a string, variable or something else but you have to use .then to access data所以你可以返回一个字符串、变量或其他东西,但你必须使用.then来访问数据

file where you make fetch request您发出获取请求的文件

export const graphql = () => {
  return fetch("https://graphqlzero.almansi.me/api", {
    "method": "POST",
    "headers": { "content-type": "application/json" },
    "body": JSON.stringify({
      query: `{
      user(id: 1) {
        id
        name
      }
    }`
    })
  })
    .then((res) => res.json()).then((responseData) => {
      console.log(responseData);
      return responseData;
    })


}

file where you call function调用函数的文件

 graphql()
 .then((e) => {
     console.log("data", e)
  });

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

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