简体   繁体   English

反应 setState 回调不会更新 state

[英]React setState callback won't update state

So I have 3 functions below.所以我有以下3个功能。 One containing calls to the two (getBooks), which are getting requests.一个包含对正在获取请求的两个 (getBooks) 的调用。 I set my state (isLoading) to true before the calls and then to true after the calls.我在调用之前将我的 state (isLoading) 设置为 true,然后在调用之后设置为 true。 This is to also make sure that the data is properly loaded.这也是为了确保正确加载数据。 However the state is not updating so, therefore, my data from the get request is invalid.但是 state 没有更新,因此,我的获取请求中的数据无效。 The callbacks in my setstate work in my other components, so I am confused.我的 setstate 中的回调在我的其他组件中工作,所以我很困惑。 Below are my 3 functions.以下是我的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 />;
        }

    }
}

It looks like you need to actually return the books value from getBooksFromIsbn .看起来您实际上需要从getBooksFromIsbn返回books值。 Await the axios call resolution and return books .等待 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; 
}

Same for handleSearch , the code needs to wait and return the resolution of the GET request.handleSearch相同,代码需要等待并返回 GET 请求的解析。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM