javascript - 第一次迭代后停止 API 请求

我正在向谷歌图书发出 API 请求,每当我收到响应时,我都想结束 api 调用。因为,我注意到当我成功发出请求并映射响应时,它仍然发出请求,并且我得到了每分钟超出配额的错误。

查看我的 api.js

我正在使用超级代理

import React, { Component } from "react"
import request from 'superagent';
import BookList from './BookList';

class Book extends Component{
    constructor(props){
      super(props);
      this.state = {
        books: [],
      }
    }
     LoadMyBooks = () => {
       request.
      get("https://www.googleapis.com/books/v1/users/101611817084652232916/bookshelves/4/volumes?key=yourKey")
      .query(null)
      .then((data) =>{
        // console.log(data);
        this.setState({books: [...data.body.items]})
        
      })
    }
    
   
   

    render(){
      const mybooks = this.LoadMyBooks();
      return(
        <div>
              <BookList books={this.state.books}/>
              
        </div>
  
  
      );
    }
    

  }

  export default Book

回答1

import React, { Component } from "react"
import request from 'superagent';
import BookList from './BookList';

class Book extends Component{
    constructor(props){
      super(props);
      this.state = {
        books: [],
      }
    }
     componentDidMount(){
       request.get("https://www.googleapis.com/books/v1/users/101611817084652232916/bookshelves/4/volumes?key=yourKey")
      .query(null)
      .then((data) =>{
        // console.log(data);
        this.setState({books: [...data.body.items]})
        
      })
    
    }
   
   

    render(){
      
      return(
        <div>
              <BookList books={this.state.books}/>
              
        </div>
  
  
      );
    }
    

  }

  export default Book

相似文章