首页 > 解决方案 > 取消承诺拒绝,从 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

标签: reactjsreact-nativeapiaxiosunhandled-promise-rejection

解决方案


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

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


推荐阅读