首页 > 解决方案 > 将 Yelp API 调用的结果总数传递给 React 组件

问题描述

GitHub 项目链接:https ://github.com/jkey774/codecademy-ravenous

几天来,我一直在尝试向我的小应用程序添加一个新功能,该功能显示从 Yelp API 调用中检索到的企业结果总数。我可以在映射每个业务之前使用 console.log(jsonResponse.total) 但我不确定如何在返回语句中将其设置为可以在 App.js 中访问 Yelp.js 的 jsonResponse.total 以执行类似 setState({总计:总计})。我是否需要进行单独的 API 调用才能获得总数?

这是响应正文的示例:

{
    "total": 8228,
    "businesses": [
      {
        "rating": 4,
        "id": "E8RJkjfdcwgtyoPMjQ_Olg",
        "review_count": 1738,
        "name": "Four Barrel Coffee",
        "image_url": "http://s3-media2.fl.yelpcdn.com/bphoto/MmgtASP3l_t4tPCL1iAsCg/o.jpg",
        "location": {
          "city": "San Francisco",
          "state": "CA",
          "address1": "375 Valencia St",
          "zip_code": "94103"
        }
      },
      // ...
    ]
}

在我的 Yelp.js 文件中:

const Yelp = {
  search(term, location, sortBy) {
    const limit = 21;
    return fetch(`https://cors-anywhere.herokuapp.com/https://api.yelp.com/v3/businesses/search?term=${term}&location=${location}&sort_by=${sortBy}&limit=${limit}`, {
      headers: {
        Authorization: `Bearer ${apiKey}`
      }
    }).then(function (response) {
      return response.json();
    }).then(function (jsonResponse) {
      if (jsonResponse.businesses) {
        return jsonResponse.businesses.map(function (business) {
          return {
            id: business.id,
            imageSrc: business.image_url,
            name: business.name,
            address: business.location.address1,
            city: business.location.city,
            state: business.location.state,
            zipCode: business.location.zip_code,
            category: business.categories[0].title,
            rating: business.rating,
            reviewCount: business.review_count
          };
        });
      }
    });
  }
};

export default Yelp;

在我的 App.js 文件中

import React from 'react';
import BusinessList from './components/BusinessList/BusinessList';
import SearchBar from './components/SearchBar/SearchBar';
import Yelp from './util/Yelp';
import './App.css';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      total: 0,
      businesses: []
    }
    this.searchYelp = this.searchYelp.bind(this);
  }
  searchYelp(term, location, sortBy) {
    Yelp.search(term, location, sortBy).then((businesses) => {
      this.setState({
        businesses: businesses
      })
    })
  }

  render() {
    return (
      <div className="App">
        <h1>ravenous</h1>
        <SearchBar searchYelp={this.searchYelp} />
        <BusinessList businesses={this.state.businesses} />
      </div>
    );
  }
}

export default App;

标签: reactjs

解决方案


欢迎来到堆栈溢出。正如您所提到的,您可以在对 setState 的一次调用中设置多个键,因此您所要做的就是获取total您的 App.js。

在 Yelp.js 中,您需要返回总数以及企业列表。您可以执行以下操作:

if (jsonResponse.businesses) {
        return {
            total: jsonResponse.total,
            businessList: jsonResponse.businesses.map(function (business) {
            // ... same code as you have before

然后,setState在 App.js 中稍微修改一下:

Yelp.search(term, location, sortBy).then((businessData) => {
      this.setState({
        businesses: businessData.businessList,
        total: businessData.total
      })
})

推荐阅读