renderQuestions部分没有问题。它打印第一个问题。问题出在renderChoices部分。我需要打印第一个问题4选择(a。)1970 b。)1971 c。)1972 d。)1973)。现在,它会打印0到3之间的数字。

import React from "react";
import axios from "axios";

class QuizApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = { questions: [], choices: [] };
  }

  componentDidMount() {
    axios
      .get("http://private-anon-c06008d89c-quizmasters.apiary-mock.com/questions")
      .then(response => {
        const allQuestions = [];
        const allChoices = [];

        response.data.forEach(({ question, choices }) => {
          allQuestions.push(question);
          allChoices.push(choices);
        });
        this.setState({ questions: allQuestions, choices: allChoices });
      });
  }

  renderQuestions = () => {
    let data = [];

    this.state.questions.map((que, i) => {
      data.push(<li key={i}>{que}</li>);
    });
    return data[0];
  };
  renderChoices = () => {
    let data = [];

    Object.keys(this.state.choices).map((ch, i) => {
      Object.keys(this.state.choices[ch]).map((cc, ii) => {
        data.push(<li key={ii}>{cc}</li>);
      });
    });
    return data;
  };
  render() {
    return (
      <div>
        {this.renderQuestions()}
        {this.renderChoices()}
      </div>
    );
  }
}

最佳答案

我不确定我为什么要提出所有问题,然后提出所有选择。我认为这只是一个测试?

给定数据的现有结构,更好的解决方案是将一个问题(及其解决方案)映射到组件。

像这样:



function Question (props) {
  return (
    <div className="Question">
      <h4>{props.question}</h4>
      <ul>
        {props.choices.map((c, i) => (
          <li className={c.correct && "correct"} key={i}>
            {c.choice}
          </li>
        ))}
      </ul>
    </div>
  );
};

class QuizApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = { questions: [] };
  }

  componentDidMount() {
    axios
      .get(
        "https://private-anon-c06008d89c-quizmasters.apiary-mock.com/questions"
      )
      .then(response => {
        this.setState({ questions: response.data });
      });
  }

  render() {
    return <div>{this.state.questions.map(q => new Question(q))}</div>;
  }
}


ReactDOM.render(<QuizApp />, document.querySelector("#app"))

#app .Question li {
  display: inline-block;
  margin: 0.5em;
}

#app .Question .correct {
  background-color: lime;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>





您现在可以轻松地修改它,一次只显示一个问题。

10-06 11:58