【问题标题】:Return the result value with fetch call function from another page, React native使用来自另一个页面的 fetch 调用函数返回结果值,React native
【发布时间】:2023-03-05 11:12:02
【问题描述】:

我需要在执行 fetch 调用的 react native 中从另一个页面返回函数的结果。我使用如下方法。据我所知,这是因为异步调用。有没有一种特殊的方法可以在 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);

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

【问题讨论】:

  • 您确定是getTestval 而不是getvals
  • @akond,抱歉,编辑问题时出错。我现在编辑了它。
  • 我看到您正在使用 react-redux 连接,但我根本没有看到 mapStateToProps 定义。你甚至都在使用它吗?你会考虑不使用 redux 的解决方案吗?

标签: javascript react-native async-await fetch-api


【解决方案1】:

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

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

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

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

【讨论】:

  • 抱歉,我知道这已经过时了,但为什么在返回 responseData 之前是 console.warn()。返回那个有什么问题还是应该是console.log()
  • 应该是console.log()。我会改的。
  • 请告诉我如何通过,我想导出函数 getvals(){ return fetch('xxx'') .then((response) => response.json()) .then(( json) => { return json.products; }) .catch((error) => { console.error(error); }); } getvals().then(response => response); const ProductsList =getvals().then(response => response);导出默认 ProductsList;
  • return fetch 没问题,但 then 中的另一个 return responseData 语句是错误的,并且不起作用!
【解决方案2】:

我认为最好的架构模式是使用回调函数,通常是作为匿名函数写入。

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

我仍然是一名初级开发人员,但经常使用这种模式。如果有人有不同方法的理由,我很想听听。

【讨论】:

  • 如何不仅使用data,还使用response
【解决方案3】:

fetch 总是返回一个 Promise 与你返回什么无关。 所以你可以返回一个字符串、变量或其他东西,但你必须使用 .then 来访问数据

您发出提取请求的文件

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


}

调用函数的文件

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-27
    • 2016-08-30
    • 1970-01-01
    • 2022-01-23
    • 2020-05-26
    • 1970-01-01
    • 2016-04-22
    • 2021-09-05
    相关资源
    最近更新 更多