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

帅气的男人

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

这是我的相关代码:

主屏幕.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>
  );
}
}

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

类别屏幕.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 文档说

可以使用 /Search API 以类别 ID 作为输入获取归入特定餐厅类型的所有餐厅的列表

每个类别 ID 都是一个特定的数字,位于apiSearchconst 中baseURL 的末尾所以我想要做的是将第一页的类别 ID 添加到第二页的 URL 末尾,因为我认为这就是我认为每个类别中的餐馆将被显示的方式。但是我开始认为这并不完全正确。我真的对如何使用 API 感到困惑

山东独山

由于您在 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>
    );
  }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用 React Native 从 API 获取数据

如何使用React Native从api加载数据

REACT NATIVE:如何在 RN 中获取 API JSON 数据

使用Redux从API在React Native中获取数据

如何使用react-native-link-preview从URL获取标题

React Native如何同时获取多个API?

如何在 React Native 中从 API 端点获取完整数据后显示数据?

如何从多个状态中过滤数据以React Native的方式从单独的API获取数据

如何使用AsyncStorage React Native缓存API数据

如何在React Native的API URL中传递变量?

如何在React Native EXPO中的Dropdown选项中动态获取api数据

如何从WooCommerce API获取产品数据到我的React Native应用中

如何在React Native中基于用户搜索从api获取数据?

API成功获取数据后如何在React Native中调用渲染

REACT NATIVE:如何获取API数据(JSON)并将其插入Flatlist

在与axios的react-native中使用POST方法获取API数据

如何使用 react-native-dropdown 获取数据 JSON?

如何使用 axios 在 React Native 中获取数据

如何使用移动相机在React Native中拍照并获取数据

react-native 从 REST Api 获取数据失败

React Native从父级与子级的API获取数据

如何从React Native Webview中的URL GET参数获取值?

如何在react js URL中传递参数以从api获取数据

React Native - 无法获取 API

React Native如何每隔X分钟从api获取

如何使用从React中的API获取的数据打开Bootstrap模式?

如何通过使用axois从React中的api获取数据?

使用 React 从 API 正确获取数据

使用React挂钩从API重新获取数据