簡體   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