reactjs - 取消承诺拒绝,从 API 获取数据
问题描述
export class Diet extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
};
}
updateSearch = (e) => {
axios
.get(
`https://api.spoonacular.com/food/products/search?apiKey{1234}&number=100`
)
.then((res) => {
this.setState({ data: res.data });
});
};
render()
return(
<SearchBar
placeholder="Search Food..."
onChangeText={this.updateSearch}
value={data}
/>
<List style={{ paddingTop: hp("2%") }}>
<TouchableOpacity>
{this.state.data.map(({ type }) => (
<Text>{this.state.type.products.title}</Text>
))}
</TouchableOpacity>
</List>
大家好,我正在尝试从 Spoonacular 数据库中获取数据axios
,我正在尝试使用 搜索食物SearchBar
并在列表中显示内容,我是编程新手,我不太确定我在正在做,当我运行它告诉我的代码时[Unhandled promise rejection: Error: Request failed with status code 400]
,列表上没有显示任何内容。
文档链接:https ://spoonacular.com/food-api/docs#Search-Grocery-Products
解决方案
您缺少query
参数。根据文档,它是必需的。所以一个正确的请求是这样的
let query = ...; //get hte value from the searchbar
axios
.get(
`https://api.spoonacular.com/food/products/search?query=${encodeURIComponent(query)}&apiKey=1234&number=100`
)
.then((res) => {
this.setState({ data: res.data });
})
.catch(error => {
console.log(error.response.data);
});
错误响应的主体可能会包含一个提示......
推荐阅读
- python - PyTorch 线性层中的尺寸不匹配
- html - 选择菜单以将变量传递给函数以更改内部html
- logging - Elixir 记录器后端:系统如何调用 init()?
- android - 如何在最新的 Android SDK 更新中使用 notificationBuilder.setSmallIcon(icon)?
- python - 在实际 pyFFTW 中计算拉普拉斯算子
- c - 这个函数可以兼容两个版本的 POSIX 吗?
- ruby - 如何在Ruby中将浮点值转换为整数
- java - 如何修复“邮件服务器连接失败;嵌套异常是 javax.mail.MessagingException:无法将套接字转换为 TLS;”使用 Spring-mvc?
- sql - SQL JOIN:在 JOIN 子句中添加自定义约束
- excel - 使 B 列中的单元格显示 A 列中的最大值