【问题标题】:Unhandle promise rejection, getting data from API未处理的承诺拒绝,从 API 获取数据
【发布时间】:2021-06-21 07:45:23
【问题描述】:
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>

大家好,我正在尝试使用 axios 从 Spoonacular 数据库中获取数据,我正在尝试使用 SearchBar 搜索食物并在列表中显示内容,我是编程新手我不太确定自己在做什么,当我运行代码时它告诉我[Unhandled promise rejection: Error: Request failed with status code 400] 并且列表上没有显示任何内容。

文档链接:https://spoonacular.com/food-api/docs#Search-Grocery-Products

【问题讨论】:

  • 正如错误所说。请求失败,并且由于您没有添加 .catch,因此拒绝未处理。您可能没有正确请求 API。
  • 谢谢,我添加了.catch,但无法弄清楚API请求有什么问题

标签: reactjs react-native api axios unhandled-promise-rejection


【解决方案1】:

您缺少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);
  });

错误响应的主体可能会包含一个提示...

【讨论】:

  • 你是对的,问题是如果我插入query=pizza,将显示的唯一结果是比萨饼,如何使用SearchBar 的输入更改查询
  • 我没有使用 react 或 react-native,所以我无法帮助您如何从搜索栏获取值。但是一旦你得到它,你可以简单地将它添加到上面显示的查询中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-31
  • 2023-03-17
  • 2018-04-01
  • 2021-09-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多