在 React Native Expo 应用程序中获取

Sam*_*Sam 3 react-native expo

fetch在我的React Native应用程序中使用Expo. 我遇到的问题是,在承诺解决之前,似乎有一个代码执行会引发错误。这是我的代码:

renderWithData() {
    return fetch('https://myapi.com')
    .then((response) => response.json())
    .then((myListData) => {
      return (
        <FlatList data={myListData} renderItem={({item}) => <Text>{item.dataItem}</Text>} />
      );
    })
    .catch((error) => {
      console.error(error);
    });
}
Run Code Online (Sandbox Code Playgroud)

我收到的错误如下:

不变违规:对象作为 React 子对象无效(发现:带有键 {_40, _65, _55, _72} 的对象)。如果您打算渲染子集合,请改用数组。

那是因为我似乎得到了某种我认为代表承诺的对象。这会引发错误。仅仅一瞬间,我就从 API 调用中获取了数组。

调用的代码renderWithData()如下:

<View style={styles.listContainer}>
   {this.renderWithData()}
</View>
Run Code Online (Sandbox Code Playgroud)

我如何让它等到收到数据。我认为使用then可以做到这一点,但显然它不起作用。

Pri*_*dya 6

fetch api 返回文档中提到的承诺。因此,您在函数中返回 a而不是promisethis.renderWithData()React Element

您必须setState将从中获取的数据并在asfetch api中动态呈现它FlatList

state = {
 myListData: []
}

renderWithData = () => { . //... Ignore if already bound
    return fetch('https://myapi.com')
    .then((response) => response.json())
    .then((myListData) => {
      this.setState({myListData}}
    })
    .catch((error) => {
      console.error(error);
    });
}

<View style={styles.listContainer}>
   <FlatList data={this.state.myListData} renderItem={({item}) => <Text>{item.dataItem}</Text>} />
</View>
Run Code Online (Sandbox Code Playgroud)

假设最后一个片段中getPhoneExtensions()提到了这一点renderWithData()