Yelp API业务搜索无法在react native中使用axios -返回空数组

x7rlezfr  于 2023-01-13  发布在  iOS
关注(0)|答案(1)|浏览(147)

Yelp API工作时遇到了麻烦,它应该基于术语集搜索企业。我使用异步等待函数来获取企业/搜索对象,然后设置参数,然后使用setResults更新状态

import React, { useState } from "react";
import { View, Text, StyleSheet } from "react-native";
import SearchBar from "../components/SearchBar";
import yelp from "../api/yelp";

const SearchScreen = () => {
const [term, setTerm] = useState("");
const [results, setResults] = useState([]);

console.log(results);
console.log(term);

const searchApi = async () => {
 try {
   const response = await yelp.get("/search", {
     params: {
       limit: 50,
       term,
       location: "san jose",
     },
   });
   setResults(response.data.businesses);
 } catch (err) {
   console.log(err);
 }
};

return (
 <View style={styles.background}>
   <SearchBar term={term} onTermChange={setTerm} onTermSubmit={searchApi} />
   <Text>We have found {results.length} results </Text>
 </View>
);
};

const styles = StyleSheet.create({});

export default SearchScreen;

下面是SearchBar组件

import React from "react";
import { View, TextInput, StyleSheet } from "react-native";
import { Feather } from "@expo/vector-icons";

const SearchBar = ({ term, onTermChange, onTermSubmit }) => {
  return (
    <View style={styles.backgroundStyle}>
      <Feather name="search" style={styles.iconStyle} />
      <TextInput
        autoCapitalize="none"
        autoCorrect={false}
        style={styles.inputStyle}
        placeholder="Search"
        value={term}
        onChangeText={onTermChange}
        onEndEditing={onTermSubmit}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  backgroundStyle: {
    backgroundColor: "#FFF",
    height: 50,
    borderRadius: 5,
    marginHorizontal: 15,
    top: 15,
    flexDirection: "row",
    marginBottom: 20
  },
  inputStyle: {
    flex: 1,
    borderRadius: 5,
    fontSize: 18,
  },
  iconStyle: {
    fontSize: 35,
    alignSelf: "center",
    marginHorizontal: 15,
  },
});

export default SearchBar;

这里是我使用axios设置baseUrl和header的地方

import axios from "axios";

export default axios.create({
  baseURL: "https://api.yelp.com/v3/businesses",
  headers: {
    Authorization:
      "BearerZPzXkPFyF_mWgHVjj_a1QZqiFkktt_iXYcX8JED6Gp2i73aYJTsvfUSApIVh7w8B8CNYfwnvBKo50MZvR34dvO3Cm1tQxlFp_PnGgCFjce1h0I1UF3zcKHnr7eq8YnYx",
  },
});

任何帮助是非常感谢我的控制台。记录的结果和术语,以确保我所有的状态是工作,它是这样,它必须是一些问题,我如何得到的yelp API。我的结果总是返回一个空数组。

控制台记录时

{result}只显示了一个空数组的起始状态-
{term}显示已键入内容的状态

预期成果

{result}应该显示在圣何塞地区匹配“pasta”的对象的数组,并且Text中的数字应该显示结果。length

dgtucam1

dgtucam11#

我尝试了您的repo。起初我得到了一个401错误,因为auth令牌中没有空间

sdk_gphone_x86_arm:
Error: "Request failed with status code 401" in

然后得到400作为无效令牌

sdk_gphone_x86_arm:
start
sdk_gphone_x86_arm:
Error: "Request failed with status code 400" in

修正后,应用程序运行成功,你可以尝试在https://snack.expo.dev/@anthnoycc/searchscreen

相关问题