首页 > 解决方案 > REST API 一次只显示一个对象

问题描述

我正在训练通过反应变得更好,并正在构建一个测验 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;

标签: javascriptjsonreactjs

解决方案


尝试这个:

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;

推荐阅读