其余API一次仅显示一个对象

时间:2019-05-23 18:18:28

标签: javascript json reactjs

我正在训练如何通过React变得更好,并正在构建一个测验API,从其余API的JSON列表中提取10个随机问题和答案。

我想知道是否有办法拆分这10个问题,使它们不会一次全部出现,而是在回答完前一个问题后一次出现。我应该使用哪种方法来实现这一目标?是split()吗?还是其他方法?或者有人可以将我引导到教程等中,他们在那里实际演示了这一点。过去几天我一直在谷歌上搜索,但是我什么都没发现。

编辑:我正在添加代码,因为这似乎比我想象的要复杂得多。

import React, { Component } from "react";
import "./App.css";

const API =
  "https://opentdb.com/api.php?amount=10&category=20&difficulty=medium";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      results: [],
      score: [],
      question: ""
    };
  }

  componentDidMount() {
    this.setState({
      question: this.state.question
    })
    this.populateAppWithData();
  }

  populateAppWithData() {
    const showData = fetch(API)
      .then(response => response.json())
      .then(data => this.setState({ results: data.results }));
    console.log(showData);
  }

  render() {
    return (
      <div className="App">
        <h1>Quiz App</h1>
        <TheCounter question={this.state.results}
          Counter={this.state.score}
          right={this.state.correct_answer}
        />
      </div>
    );
  }
}
class MythologyAnswers extends Component {
  constructor(props) {
    super(props);
    this.state = {
      answered: undefined, isRight: undefined
    };
  }
  answerClicked(answer) {
    const { hasAnswered, correct_answer } = this.props;
    return event => {
      if (this.state.answered) return;
      const isRight = correct_answer === answer;
      hasAnswered(isRight);
      this.setState({ answered: answer, isRight });
    }
  }

  render() {
    const { question, correct_answer, incorrect_answers } = this.props;
    const { answered, isRight } = this.state;
    return (
      <div className="newQuestion">{question}
        {[...incorrect_answers, correct_answer]
          .map(answer => <div onClick={this.answerClicked(answer)}>{answer} </div>)} <br />
        {answered && `You answered ${answered}`} <br />
        <div className="correctAnswer"> {answered && isRight && "This is correct!"} </div>
        <div className="incorrectAnswer"> {answered && !isRight && "This is incorrect. please try again"} </div>
      </div>
    )
  }
}

class TheCounter extends Component {
  constructor(props) {
    super(props);
    this.state = {
      right: 0,
      Counter: 0,
    };

  }
  questionAnswered(isRight) {
    this.setState(({ Counter, right }) => ({ Counter: Counter + 1, right: right + isRight }));
  }

  render() {
    const { question } = this.props;
    const { Counter, right } = this.state;

    return (
      <div className="newQuestion">
        {question.slice().map(i => <MythologyAnswers key={i.question} {...i}
          hasAnswered={it => this.questionAnswered(it)} />)}
        <div>Counter: {this.state.Counter}</div>
      </div>
    )
  }
}
export default App;

2 个答案:

答案 0 :(得分:1)

尝试:

import React, { Component } from "react";
import "./App.css";


const API =
  "https://opentdb.com/api.php?amount=10&category=20&difficulty=medium";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      results: [],
      score: []
    };
  }

  componentDidMount() {
    this.populateAppWithData();
  }

  populateAppWithData() {
    fetch(API)
      .then(response => response.json())
      .then(data => this.setState({ results: data.results }));
  }

  render() {
    const { results } = this.state;

    return (
      <div className="App">
        <h1>Quiz App</h1>
        <TheCounter
          results={results}
          Counter={this.state.score}
          right={this.state.correct_answer}
        />
      </div>
    );
  }
}
class MythologyAnswers extends Component {
  constructor(props) {
    super(props);
    this.state = {
      prevAnswer: "",
      isRight: null
    };
  }
  answerClicked(answer) {
    const { hasAnswered, correct_answer } = this.props;
    return event => {
      const isRight = correct_answer === answer;
      hasAnswered(isRight);
      this.setState({ prevAnswer: answer, isRight });
    };
  }

  render() {
    const { question, correct_answer, incorrect_answers } = this.props;
    const { prevAnswer, isRight } = this.state;
    return (
      <div className="newQuestion">
        {question}
        {incorrect_answers &&
          incorrect_answers
            .concat(correct_answer)
            .map(answer => (
              <div onClick={this.answerClicked(answer)}>{answer}</div>
            ))}{" "}
        <br />
        {prevAnswer && `You answered ${prevAnswer}`} <br />
        <div className="correctAnswer">
          {" "}
          {prevAnswer && isRight && "This is correct!"}{" "}
        </div>
        <div className="incorrectAnswer">
          {" "}
          {prevAnswer && !isRight && "This is incorrect. please try again"}{" "}
        </div>
      </div>
    );
  }
}

class TheCounter extends Component {
  constructor(props) {
    super(props);
    this.state = {
      right: 0,
      Counter: 0
    };
  }
  questionAnswered = isRight => {
    this.setState(({ Counter, right }) => ({
      Counter: Counter + 1,
      right: right + isRight // isRight is a boolean. why are we using addition here?
    }));
  };

  render() {
    const { results } = this.props;
    const { Counter } = this.state;

    const question = results[Counter];

    return (
      <div className="newQuestion">
        <MythologyAnswers {...question} hasAnswered={this.questionAnswered} />
        <div>Counter: {this.state.Counter}</div>
      </div>
    );
  }
}

export default App;

答案 1 :(得分:0)

这将为每个测验提供Javascript alert,然后在单击“确定”时为下一个测验提供服务。您没有说是否要输入实际输入并将其与正确答案进行比较,但是通过这种方式,您可以根据需要使用所有变量。 See sample quiz

your_json 是您从API中获得的:

var your_json = {
"response_code":0,"results":[{"category":"Mythology","type":"multiple","difficulty":"medium","question":"This Greek mythological figure is the god\/goddess of battle strategy (among other things).","correct_answer":"Athena","incorrect_answers":["Ares","Artemis","Apollo"]}]
        } //// etc.



var i = 0;

function loopValues(element) {  
  return Object.values([your_json.results[i][element]]);;
}

while (i < 10) {

   var cat = loopValues('category');
   var typ = loopValues('type');
   var dif = loopValues('difficulty');
   var que = loopValues('question');
   var ans = loopValues('correct_answer');
   var not = loopValues(['incorrect_answers'][0]);

    alert("Question " + ([i+1]) + " Category: " + cat);
    alert(que);
    alert("Answer: " + ans);

i++;

}