React Native 过滤 API 以检索特定数据

React Native filtering API to retrieve specific data

我正在使用 Zomato API (https://developers.zomato.com/documentation),对于从 API 获取数据还是个新手,到目前为止我能够从 [=22] 检索类别=].但是我想做的是从特定城市提取类别数据。这是我的代码:

APIcall.js

import axios from 'axios';

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

Home.js

export default class HomeScreen extends React.Component {

  constructor(props){
    super(props);
    this.state={
      data : []
    }
  }

async  componentDidMount(){

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

 console.log(await apiCall('?cities'))//I tried console logging to see what data I can get all I get is [Error: Request failed with status code 404] undefined
  }

  render() {
    return (
      <View>

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

      </View>
    );
  }
}

根据 Zomato API 文档,为了从特定城市提取类别数据,您需要将 city_id 作为参数传递。

import React, { Component } from 'react';
import { FlatList, ActivityIndicator, Text, View } from 'react-native';
import axios from 'axios';

export default class HomeScreen extends Component {

  constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
      data: []
    }
  }

  async componentDidMount() {
    let result;
    try {
      result = await axios.request({
        method: 'GET',
        url: "https://developers.zomato.com/api/v2.1/categories?city_id=280",
        headers: {
          'Content-Type': 'application/json',
          'user-key': "a31bd76da32396a27b6906bf0ca707a2",
        },
      })
    } catch (err) {
      err => console.log(err)
    }
    this.setState({
      isLoading: false,
      data: result.data.categories
    })
  }

  render() {
    return (
      <View>
        {
          this.state.isLoading ?
            <View style={{ flex: 1, padding: 20 }}>
              <ActivityIndicator />
            </View> :
            <FlatList
              keyExtractor={item => item.id}
              data={this.state.data}
              renderItem={({ item }) =>
                <Text>{item.categories.name} </Text>
              }
            />
        }
      </View>
    );
  }
}

希望对你有帮助。