【问题标题】:React fetch not returning correct value?React fetch 没有返回正确的值?
【发布时间】:2020-05-18 07:34:31
【问题描述】:

我在 Spring Boot 中设置了我的 api,当您调用其中一个方法时,它会返回一个成功或失败的字符串。但是,我的 fetch 控制台成功,但是当我尝试将其保存到变量时,它显示未定义。如何从我的 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;
  })

【问题讨论】:

    标签: javascript reactjs api fetch


    【解决方案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;
    

    【讨论】:

    • 我发送了一个单词字符串作为响应。例如,“失败”
    • 如果是文本或字符串作为响应,请使用response.text().then(data =&gt; { console.log(text); });
    猜你喜欢
    • 1970-01-01
    • 2014-11-26
    • 2019-03-21
    • 1970-01-01
    • 2014-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多