繁体   English   中英

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

[英]REACT AXIOS: I am working on a quiz that each questin has corresponding array of choices in that index in

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

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>;
  }
}

查看网络呼叫响应后,我可以看到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>;
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM