我正在学习如何react ,我遇到了一个问题.为什么从异步函数返回时获取数据会返回一个promise ,但在异步函数本身中,它会正确地返回一个对象数组?

componentDidMount()上,我调用我的异步函数,该函数反过来获取api url:

  componentDidMount() {
    let data = this.getData();
    console.log(data);    // <-- Promise {_40: 0, _65: 0, _55: null, _72: null}
    this.setState({
      dataSource:this.state.dataSource.cloneWithRows(data),
    })  
  }

  async getData() {
    const response = await fetch("http://10.0.2.2:3000/users", {
            method: 'GET',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            }   
        }); 
    const json = await response.json();
    console.log(json);     // <-- (5) [Object, Object, Object, Object, Object]
    return json;
  }

console.log(json)中,我得到了正确的json对象列表,我可以用json[0].name访问它们.但后来,console.log(data)返回了一个包含奇数数据的promise :

Promise {_40: 0, _65: 0, _55: null, _72: null}

... 我再也找不到我的json对象了.这是为什么?更重要的是,如何在componentDidMount()中检索json数据,以便将其设置为dataSource

推荐答案

由于getData()是一个promise ,您应该能够获得then块中的数据,如下所示:

componentDidMount() {
  this.getData()
    .then((data) => {
      this.setState({
        dataSource:this.state.dataSource.cloneWithRows(data),
      })  
    });
}

React-native相关问答推荐

AxiosError:Reaction Native EXPO开发版本中的网络错误

莫迪德不会停留在屏幕中央

元素类型无效:应为字符串

如何在react native 中将选定的自定义复选框数据发送到下一页?

在 ReactNative 中调用 RCTDeviceEventEmitter.emit 时出错

react native HTML entities

_react2.default.PropTypes.function 未定义

如何在react-native 中处理不同的屏幕尺寸?

@react-navigation/stack 与 @react-navigation/native-stack 有什么区别?

React-Native Android 中隐藏(hide)的元素溢出

React native Touch 事件正在通过绝对视图

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

带有 xcode 模拟器的 react-native 有非常慢的alert

React Native vs Swift/Objective-C/Java Native

如何在不使用 JSX 的情况下在 React Native 中制作组件?

React Native 得到这个错误'Unrecognized operator abs'

在 React Native Navigator 中的组件之间传递值

如何在react-native中绘制虚线边框样式

使用 React Native 运行 Firebase 3.0 时出错

React Native + Redux 基本认证