我需要从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);

它将结果显示为"undefined",但该fetch调用工作,并显示结果.有什么建议吗?

推荐答案

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

React-native相关问答推荐

原生react :顶部的滑块位置

@testing-library/react-native -> 渲染 -> TypeError:无法读取未定义的属性(读取存在)

react-native 自定义视图,原生 prop 没有 propType

如何在 react-native 中使用 Animated 制作 svg 动画

如果没有启用远程调试器,React Native 代码将无法工作

react-native (expo)加载markdown 文件

为了回调 URL 的目的,在 Expo 中运行的 React Native 元素的 info.plist 在哪里?

React Native:错误:找不到资源 android:style/TextAppearance.Material.Widget.Button.Borderless.Colored

如何判断 React Native 中的 AsyncStorage 中是否存在密钥? getItem() 总是返回一个promise对象

React Native ScrollView 在snapping后重新回到顶部

Jest 的配置在更新到 26.x 后抛出type ErrorHandler = (error: mixed, isFatal: boolean) => void

React-Native:FlatList onRefresh not called on pull up.

在 react-native 和 firebase 3.1 中登录 Facebook

React Native - Firebase 身份验证持久性不起作用

按钮的标题属性必须是字符串

react-native:webview 高度

如何在 React Native 上隐藏 createStackNavigator 的标题?

React 本机矢量图标在当前版本 0.60 上不起作用

React Navigation 切换背景 colored颜色 和样式 StackNavigator

React Native 多行TextInput,文本居中