React setState回调不会更新状态

时间:2020-04-07 07:53:16

标签: javascript reactjs axios

所以我下面有3个功能。一个包含对两个(getBooks)的调用,这两个正在获取请求。我在调用之前将状态(isLoading)设置为true,然后在调用之后设置为true。这也是为了确保正确加载数据。但是状态没有更新,因此,来自get请求的数据无效。 setstate中的回调可在其他组件中使用,因此感到困惑。以下是我的3个功能。

import React from 'react';
import ReactDOM from 'react-dom';
import SidePane from './SidePane.js';
import HomeNavBar from './HomeNavBar.js';
import axios from 'axios';
import qs from 'qs';
import Loading from './Loading.js';

class HomePage extends React.Component {

    constructor(props) {
        super(props);
        this.state = { 
            bookSearch: "",
            bookSearchResults: [],
            bookSearchFound: false,
            isLoading: false
        };
        this.handleSearch = this.handleSearch.bind(this);
        this.alertBookName = this.alertBookName.bind(this);
        this.getBooksFromIsbn = this.getBooksFromIsbn.bind(this);
        this.getBooks = this.getBooks.bind(this);
        axios.defaults.withCredentials = true;
    }

    changeBookName = (e) => {

        var bookName = e.target.value;
        bookName = bookName.split(' ').join('+');
        this.setState({bookSearch: bookName})
    }

    getBooksFromIsbn(isbns){

        var books = [];

        axios
            .get('http://localhost:9000/api/getBooksFromIsbn',
            {
                params: {
                    books: JSON.stringify(isbns)
                }
            })
            .then(res =>
            {
                console.log(res.data);
                books = res.data;


            })
            .catch(error => {
                console.log(error.response);
            });
    }


    getBooks(){

        this.setState({
            isLoading: true
        },
            function(){console.log("setState completed", this.state)}
        );

        var bookResults = this.handleSearch();
        var books = this.getBooksFromIsbn(bookResults);

        this.setState({
            isLoading: false
        },
            function(){console.log("setState completed", this.state)}
        );
        this.props.setBookSearchResults(books);
    }


    handleSearch(){

        var bookResults = [];

        var url = 'http://localhost:9000/api/getOpenLibrarySearch';

        axios
        .get(url,
        {
            params: {
                bookSearch: this.state.bookSearch
            }
        })
        .then(res =>
        {
            //this.setState({bookSearchResults: res.data});

            for(var i=0; i < res.data.docs[i].isbn.length; i++){
                bookResults = bookResults.concat(res.data.docs[i].isbn);
            }
            console.log(bookResults);
        })
        .catch(error => {
            console.log(error.response);
        });

        return bookResults;
    }

    render(){

        if(this.state.isLoading == false){
            return(
                <div>
                    <HomeNavBar authToken = {this.props.authToken} email = {this.props.email} />
                    <SidePane changeBookName = {this.changeBookName} handleSearch = {this.getBooks} />
                </div>
            )           
        }
        else
        {
            return <Loading />;
        }

    }
}

1 个答案:

答案 0 :(得分:0)

看来您实际上需要从books返回getBooksFromIsbn值。等待axios调用解析并返回books

async getBooksFromIsbn (isbns) {
  const books = [];

  try {
    const res = await axios.get(
      'http://localhost:9000/api/getBooksFromIsbn',
      {
        params: {
          books: JSON.stringify(isbns)
        }
      });
    books = res.data;
  } catch(error) {
    console.log(error.response);
  }

  return books; 
}

handleSearch相同,代码需要等待并返回GET请求的分辨率。