REXI AXIOS:我正在做一个测验,每个测验在该索引中都有对应的选择数组。

时间:2018-07-09 11:42:24

标签: javascript reactjs axios

我不知道我的代码是否正确,但是会出现此错误:

  

TypeError:this.state.questions.map不是函数。

为什么我会遇到这种行为?

import React from "react";
import axios from "axios";
import Countdown from "react-countdown-now";

class QuizApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      questions: [],
      ch: []
    };
  }
  componentDidMount() {
    axios.get("http://private-anon-c06008d89c-quizmasters.apiary-mock.com/questions")
      .then(response => {
        const { questions, ch } = response.data;
        this.setState({ questions, ch });
      });
  }

  render() {
    <div>
      <ul>
        {this.state.questions.map((que, index) => {
          <li>{que.questions} </li>;
          {
            this.ch[index].map(choice => <li>{choice}</li>);
          }
        })}
      </ul>
    </div>;
  }
}

1 个答案:

答案 0 :(得分:0)

查看网络呼叫响应后,我可以看到response.data是数组类型。但是,当您应用对象分解来获取问题时,它将获得未定义的值。因此,渲染时的地图失败,因为this.state.questions未定义。

import React from 'react';
import axios from 'axios';
import Countdown from 'react-countdown-now';

class QuizApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      questions: [],
      ch: [],
    };
  }
  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, ch: allChoices});
      });
  }

  render() {
    <div>
      <ul>
        {this.state.questions.map((que, index) => {
          <li>{que.questions} </li>;
          {
            this.ch[index].map((choice) => <li>{choice}</li>);
          }
        })}
      </ul>
    </div>;
  }
}