[英]Yelp Api business search not working in react native using axios - returns an empty array
无法让 yelp api 正常工作,它应该根据术语集搜索企业。 我正在使用异步等待 function 获取业务/搜索 object,然后设置我的参数,然后使用 setResults 更新 state
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",
},
});
非常感谢任何帮助我控制台记录了结果和术语,以确保我的所有 state 都正常工作,所以它必须是我如何获得 yelp api 的一些问题。我的结果总是返回一个空数组。
登录控制台时
{result} 只显示一个空数组开始 state –
{term} 显示输入的任何内容的 state
预期结果
{result} 应该显示 arrays 个与圣何塞地区的“意大利面”匹配的对象,文本中的数字应该显示 results.length
我试过你的回购。 起初我收到401
错误,因为身份验证令牌中没有空格
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中尝试
嘿,我正在同一门课程中学习 React Native,我认为我们使用的 api 密钥已过期,我们必须获得一个新密钥才能检索一些数据
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.