我想分解我的api并使用react返回它如何在用例中实现呢?

问题描述 投票:0回答:1

我希望能够获取我的api并返回它,但是我无法破坏外部响应。当我在控制台中检查时,api返回了,并且响应中填充了正确的json,但是我不确定为什么我无法访问结果数组并显示问题以及其他返回的键值对。我目前遇到映射错误,提示地图未定义。

Index.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"));

Api的Json文件

 {
"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"
  ]
  }
  ]
  }
arrays json reactjs api destructuring
1个回答
0
投票

您在fetchQuestions方法中有一个错误。您应该使用res.json()而不是res.results。请检查下面的示例,并使用以下代码replace您的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})
            });
    }
© www.soinside.com 2019 - 2024. All rights reserved.