React Native 如何使用 API URL 获取数据

React Native how to fetch data with API URL

我正在尝试从 Zomato API (https://developers.zomato.com/documentation) 中检索数据,并且我正在尝试从选定的类别中检索餐馆。这是我第一次使用 APIs,所以如果有人可以指导我解决我不理解的问题,或者如果我的代码中有错误,我将不胜感激。

这是我的相关代码:

HomeScreen.js

async componentDidMount(){
  this.setState({
    data: await apiCall('')
  })
}

render() {
  return (
    <View>
      <FlatList
        style={{ marginBottom: 80 }}
        keyExtractor={item => item.id}
        data={this.state.data}
        renderItem={({ item }) =>
          <TouchableHighlight onPress={() => this.props.navigation.navigate('CategoryScreen', { category: item.categories.id })}>//the user will tap on the category and the CategoryID will be moved to the next screen
            <Card style={styles.container}>
              <Text style={{ color: '#000', fontWeight: 'bold' }}>{item.categories.name} </Text>
            </Card>
          </TouchableHighlight>}
      />
    </View>
  );
}
}

一旦用户点击平面列表中的类别单元格,项目应在下一页中列出该类别中的所有餐厅

CategoryScreen.js

 async componentDidMount(){
  this.setState({
    data: await apiSearch('`{this.props.navigate.category}`')
  })
  console.log(await apiSearch)
}

render(){
  return (
    <FlatList
      style={{ marginBottom: 80 }}
      keyExtractor={item => item.id}
      data={this.state.data}
      renderItem={({ item }) =>
        <Card style={styles.container}>
          <Text style={{ color: '#000', fontWeight: 'bold' }}>{item.restaurants.name} </Text>
        </Card>}
    />
  );
}

这是我拥有所有 API 调用函数的文件

API.js

import axios from 'axios';

export const apiCall = async () => {
  return await axios.request({
    baseURL: "https://developers.zomato.com/api/v2.1/categories?city_id=New%20Jersey%20",
    headers: {
      'user-key': "a31bd76da32396a27b6906bf0ca707a2",
    },
    method: 'get'
  }).then(async (response) => {
    return response.data.categories
  }).catch(err => console.log(err))
}

export const apiSearch = async (id) => {
  return await axios.request({
    baseURL: `https://developers.zomato.com/api/v2.1/search?category=${id}`,
    headers: {
      'user-key': "a31bd76da32396a27b6906bf0ca707a2",
    },
    method: 'get'
  }).then(async (response) => {
    return response.data.restaurants
  }).catch(err => console.log(err))
}

根据 Zomato API 文档说

List of all restaurants categorized under a particular restaurant type can be obtained using /Search API with Category ID as inputs

每个类别 ID 都是一个特定的数字,位于 apiSearch 常量中基数 URL 的末尾。所以我要做的是将第一页的类别 ID 添加到第二页的 URL 末尾,因为我认为这就是每个类别中的餐厅的显示方式。但是我开始认为这并不完全正确。我真的很困惑如何使用 APIs

试试这个

 async componentDidMount(){
     let response = await apiSearch('`{this.props.navigate.category}`')
     console.log(response)
     this.setState({
       data: response
     }) 
 }

由于您在 HomeScreen.js 中传递选定的类别 ID,您可以从 CategoryScreen.js 访问该值,如下所示,

this.props.navigation.navigation.state.params.category

现在您需要将该值作为参数传递给 https://developers.zomato.com/api/v2.1/search

async componentDidMount() {
    let id = this.props.navigation.state.params.category
    let result;
    try {
      result = await axios.request({
        method: 'GET',
        url: `https://developers.zomato.com/api/v2.1/search?category=${id}`,
        headers: {
          'Content-Type': 'application/json',
          'user-key': "a31bd76da32396a27b6906bf0ca707a2",
        },
      })
    } catch (err) {
      err => console.log(err)
    }
    this.setState({
      isLoading: false,
      data: result.data.restaurants
    })
  }

终于可以显示里面的数据了CategoryScreen.js

render() {
    return (
      <View>
        {
          this.state.isLoading ?
            <View style={{ flex: 1, padding: 20 }}>
              <ActivityIndicator />
            </View> :
            (
              this.state.data.length == 0 ?
                <View style={{ flex: 1, padding: 20 }}>
                  <Text style={{ color: '#000', fontWeight: 'bold' }}>No restaurants from selected category</Text>
                </View> :
                <FlatList
                  style={{ marginBottom: 80 }}
                  keyExtractor={item => item.id}
                  data={this.state.data}
                  renderItem={({ item }) =>
                    <Text style={{ color: '#000', fontWeight: 'bold' }}>{item.restaurant.name} </Text>
                  }
                />
            )
        }
      </View>
    );
  }