Я хотел бы деструктурировать свой API и вернуть его с помощью реакции Как я могу добиться этого в моем сценарии использования? - PullRequest
0 голосов
/ 01 мая 2020

Я хотел бы иметь возможность получить мой API и вернуть его, однако я не в состоянии разрушить внешний ответ. Когда я проверяю свою консоль, API возвращается, и ответ заполняется правильными json, однако я не совсем уверен, почему я не могу получить доступ к массиву результатов и отобразить вопросы вместе с другими парами возвращаемых значений ключа , В настоящее время я получаю сообщение об ошибке, сообщающее, что карта не определена.

Индекс. js

 import React, { Component } from "react";
 import ReactDOM from "react-dom";
 import Hello from "./Hello";
 import "./style.css";

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

fetchQuestions() {
fetch(`https://opentdb.com/api.php? 
   amount=10&difficulty=hard&type=boolean`)
  .then(res => res.results)
  .then(data =>
    this.setState({
      questions: data,
      isLoading: false
    })
  )
  .catch(error => this.setState({ error, isLoading: false }));
  }

  componentDidMount() {
  this.fetchQuestions();
   }
  render() {
  const { isLoading, questions, error } = this.state;
  return (
  <React.Fragment>
    <h1>Random User</h1>
    {error ? <p>{error.message}</p> : null}
    {!isLoading ? (
      questions.results.map(questions => {.    //something right here 
      //is erroring
        const { category, type, difficulty } = questions;
        return (
          <div key={category}>
            <p>Question Type: {type}</p>
            <p>Difficulty: {difficulty}</p>
            <hr />
          </div>
        );
      })
    ) : (
      <h3>Loading...</h3>
    )}
    </React.Fragment>
    );
    }
    }

    ReactDOM.render(<App />, document.getElementById("root"));

Json Файл из Api

 {
"response_code": 0,
"results": [
{
  "category": "Entertainment: Video Games",
  "type": "boolean",
  "difficulty": "hard",
  "question": "The retail disc of Tony Hawk&#039;s Pro Skater 5 only 
  comes with the tutorial.",
  "correct_answer": "True",
  "incorrect_answers": [
    "False"
  ]
},
{
  "category": "Science: Mathematics",
  "type": "boolean",
  "difficulty": "hard",
  "question": "The binary number &quot;101001101&quot; is equivalent 
 to the Decimal number &quot;334&quot;",
  "correct_answer": "False",
  "incorrect_answers": [
    "True"
  ]
},
{
  "category": "Science & Nature",
  "type": "boolean",
  "difficulty": "hard",
  "question": "Scientists can grow teeth from urine.",
  "correct_answer": "True",
  "incorrect_answers": [
    "False"
  ]
},
{
  "category": "Entertainment: Video Games",
  "type": "boolean",
  "difficulty": "hard",
  "question": "In Undertale, having a &quot;Fun Value&quot; set to 56- 
57 will play the &quot;Wrong Number Song Call&quot;.",
  "correct_answer": "False",
  "incorrect_answers": [
    "True"
  ]
},
{
  "category": "Entertainment: Japanese Anime & Manga",
  "type": "boolean",
  "difficulty": "hard",
  "question": "Throughout the entirety of &quot;Dragon Ball Z&quot;, 
 Goku only kills two characters: a miniboss named Yakon and Kid Buu.",
  "correct_answer": "True",
  "incorrect_answers": [
    "False"
  ]
},
{
  "category": "Geography",
  "type": "boolean",
  "difficulty": "hard",
  "question": "Switzerland has four national languages, English being 
one of them.",
  "correct_answer": "False",
  "incorrect_answers": [
    "True"
  ]
},
{
  "category": "Entertainment: Music",
  "type": "boolean",
  "difficulty": "hard",
  "question": "The band STRFKR was also briefly known as Pyramiddd.",
  "correct_answer": "True",
  "incorrect_answers": [
    "False"
  ]
},
{
  "category": "Science & Nature",
  "type": "boolean",
  "difficulty": "hard",
  "question": "The chemical element Lithium is named after the country 
 of Lithuania.",
  "correct_answer": "False",
  "incorrect_answers": [
    "True"
  ]
},
{
  "category": "Entertainment: Japanese Anime & Manga",
  "type": "boolean",
  "difficulty": "hard",
  "question": "Druid is a mage class in &quot;Log Horizon&quot;.",
  "correct_answer": "False",
  "incorrect_answers": [
    "True"
  ]
},
{
  "category": "Vehicles",
  "type": "boolean",
  "difficulty": "hard",
  "question": "The term &quot;GTO&quot; was originated by Ferrari?",
  "correct_answer": "True",
  "incorrect_answers": [
    "False"
  ]
  }
  ]
  }

1 Ответ

0 голосов
/ 01 мая 2020

У вас ошибка в методе fetchQuestions . Вы должны использовать res. json () вместо res.results . Пожалуйста, проверьте приведенный ниже пример и замените ваш fetchQuestions метод на следующий код:

fetchQuestions() {
        fetch(`https://opentdb.com/api.php?amount=10&difficulty=hard&type=boolean`)
            .then(res => res.json())
            .then(data =>
                this.setState({
                    questions: data,
                    isLoading: false
                })
            )
            .catch(error => this.setState({error, isLoading: false}));
    }

Аналогичный код с проверкой кода статуса:

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})
            });
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...