反应获取未返回正确的值?

时间:2020-05-18 07:34:31

标签: javascript reactjs api fetch

我在Spring Boot中设置了我的api,当您调用其中一种方法时,它返回成功或失败的字符串。但是,我的提取成功了,但是当我尝试将其保存到变量中时,它表示未定义。如何从api中获取成功或失败字符串?

    handleSubmit(event) {
  var a ;
  event.preventDefault();
this.setState({username:'poop'})
console.log("submit");
  fetch('http://localhost:8080/login/'+this.state.username+'/'+this.state.password,{
    method: 'GET',


  }).then((resp)=> resp.text())
  .then(function(data){
a= data;
  })

1 个答案:

答案 0 :(得分:1)

我希望您将响应作为json发送。如果是,请使用 .then((resp)=> resp.json())。请检查以下使用fetch调用api的完整示例。

import React, {Component} from "react";

class FetchExample extends React.Component {
    state = {
        isLoading: false,
        questions: [],
        error: null
    };

    async fetchQuestions(){
        fetch(`https://opentdb.com/api.php?amount=10&difficulty=hard&type=boolean`,)
            .then(response => {
                    if (response.status !== 200) {
                        console.log('There was a problem. Status Code: ' + response.status);
                        return;
                    }
                    response.json().then(data => {
                        console.log(data);
                        this.setState({
                            questions: data,
                            isLoading: false
                        })
                    });
                }
            )
            .catch(function (error) {
                console.log('Error: ', error);
                this.setState({error, isLoading: false})
            });
    };

    render() {
        const {isLoading, questions, error} = this.state;
        return (
            <React.Fragment>
                <h1>Random Question</h1>
                <button onClick={this.fetchQuestions}>Click for calling API using fetch</button>
                {error ? <p>{error.message}</p> : null}

                {!isLoading && questions.results ? (
                    questions.results.map((questions, index) => {    //something right here
                        //is erroring
                        const {question, category, type, difficulty} = questions;
                        return (
                            <div key={index}>
                                <p>Question: {question}</p>
                                <p>Question Type: {type}</p>
                                <p>Difficulty: {difficulty}</p>
                                <hr/>
                            </div>
                        );
                    })
                ) : isLoading ? (
                    <h3>Loading...</h3>
                ) : null}
            </React.Fragment>
        );
    }
}
export default FetchExample;