Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript React setState回调赢了';更新状态_Javascript_Reactjs_Axios - Fatal编程技术网

Javascript React setState回调赢了';更新状态

Javascript React setState回调赢了';更新状态,javascript,reactjs,axios,Javascript,Reactjs,Axios,下面我有3个函数。一个包含对两个(getBooks)的调用,这两个都在获取请求。我在调用之前将我的状态(isLoading)设置为true,然后在调用之后将其设置为true。这也是为了确保数据正确加载。但是,状态没有更新,因此,get请求中的数据无效。setstate中的回调在其他组件中工作,因此我感到困惑。下面是我的3个功能 import React from 'react'; import ReactDOM from 'react-dom'; import SidePane from './

下面我有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 />;
        }

    }
}
从“React”导入React;
从“react dom”导入react dom;
从“./SidePane.js”导入侧窗格;
从“./HomeNavBar.js”导入HomeNavBar;
从“axios”导入axios;
从“qs”进口qs;
从“/Loading.js”导入加载;
类。组件{
建造师(道具){
超级(道具);
this.state={
图书搜索:“,
图书搜索结果:[],
图书搜索结果:错误,
孤岛加载:false
};
this.handleSearch=this.handleSearch.bind(this);
this.alertBookName=this.alertBookName.bind(this);
this.getbooksfromsbn=this.getbooksfromsbn.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})
}
从ISBN获取图书(isbns){
var账簿=[];
axios
.get('http://localhost:9000/api/getBooksFromIsbn',
{
参数:{
书籍:JSON.stringify(isbns)
}
})
。然后(res=>
{
console.log(res.data);
书籍=资源数据;
})
.catch(错误=>{
console.log(error.response);
});
}
getBooks(){
这是我的国家({
孤岛加载:正确
},
函数(){console.log(“setState completed”,this.state)}
);
var bookResults=this.handleSearch();
var books=this.getbooksfromsbn(bookResults);
这是我的国家({
孤岛加载:false
},
函数(){console.log(“setState completed”,this.state)}
);
此.props.setBookSearchResults(书籍);
}
handleSearch(){
var bookResults=[];
var url='1〕http://localhost:9000/api/getOpenLibrarySearch';
axios
.get(url,
{
参数:{
bookSearch:this.state.bookSearch
}
})
。然后(res=>
{
//this.setState({bookSearchResults:res.data});
对于(var i=0;i{
console.log(error.response);
});
返回记账结果;
}
render(){
if(this.state.isLoading==false){
返回(
)           
}
其他的
{
返回;
}
}
}

看起来您实际上需要从
getbooksfromsbn
返回
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; 
}

对于
handleSearch
,代码需要等待并返回GET请求的解决方案。

“但是状态没有更新”-为什么您希望它在“更改”时更新它从
true
true
?旁白:
handleSearch
总是返回一个空数组,
getBooksFromIsbn
总是返回
undefined
。你能不能显示整个组件,需要知道什么时候调用getBooks。此外,如果可以的话,请在codesandbox中创建一个工作示例。@Quentin抱歉,我实际上将它们都设置为true,只是为了看看它是否会改变它们,因为isLoading默认为false。我更新了我的代码above@Quentin你能给我一些关于如何不使它们返回为空和未定义的见解吗?我将函数更改为async,并等待对handleSearch和getBooksFromIsbn的两个调用,但是返回的书籍最终都是未定义的