簡體   English   中英

在反應輪詢中從 API 獲取數據

[英]fetching data from API in react poll

我想從 API 獲取數據並使用 React 顯示前端,但我從前端收到錯誤(TypeError: answers.map is not a function )所以我該如何解決這個錯誤 -

我的代碼是 -

import React, { useState, useEffect } from "react";
import Poll from "react-polls";
import { getPolls } from "../helper/coreapicalls";

const MainPoll = () => {
  const [polls, setPoll] = useState([]);
  const [error, seterror] = useState(false);
  // Setting answers to state to reload the component with each vote
  const [pollAnswers, setPollAnswers] = useState([]);

  useEffect(() => {
    loadPoll();
  }, []);

  const loadPoll = () => {
    getPolls().then((data) => {
      if (data.error) {
        seterror(data.error);
      } else {
        setPoll(data);
        console.log(data);
      }
    });
  };

  // Handling user vote
  // Increments the votes count of answer when the user votes
  const handalchange = () => {
    console.log("hello");
  };

  return (
    <div className="">
      <div className="container">
        <h1 className="blog_heading">Poll's of the Day</h1>
        <div className="row">
          {polls.map((poll, index) => (
            <div className="col-lg-4 col-12" key={index}>
              <Poll
                question={poll.question}
                answers={poll.options.none}
                onVote={handalchange}
              />
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

export default MainPoll;

我從 API 獲得的數據是- 在此處輸入圖像描述 在這里我有問題,3 個選項如何顯示給前端

錯誤 - 在此處輸入圖像描述

您向我們展示的代碼中有兩個小錯誤:

  1. 您導入的第一個import Polls from "./polls"; 並且您調用<Poll noStorage question={poll.question} answers={poll.options} onVote={handleVote}/>只需更改 Poll by Polls。
  2. const [pollAnswers, setPollAnswers] = useState([...answers]); 這沒有用,因為您需要為 state 傳遞一個初始值,而answer尚未初始化和可訪問。 只需更改useState([...answers]); 通過useState([]);
    更新
    您需要將數組傳遞給 answers 道具。 我們可以在您的控制台屏幕截圖中看到,選項數組以“none”作為鍵,所以試試這個: <Poll noStorage question={poll.question} answers={poll.options.none} onVote={handleVote}/> ("無”是一個奇怪的鍵...)
    更新
    您的數據 object 的格式不適合 react-polls answers 道具。 react-polls的 npmjs 文檔中,我們可以看到一個選項示例,它是一個 object 的數組,如下所示:
[
  { option: 'Yes', votes: 8 },
  { option: 'No', votes: 2 }
]

因此,根據您在問題中添加的數據控制台日志,它應該如下所示:

[
  {
    createdAt: "2020-12-01T21:43:23:21.061Z",
    options: {
      none: [ { option: 'Yes', votes: 8 },
      { option: 'No', votes: 2 }],
      student: ["12345678978945"],
      teacher: ["7894567894231"]
    },
    question: "Are you student ot teacher",
    updatedAt: "2020-12-01T21:43:23:21.061Z"
  }
]

在此處查看一個沙盒與您的代碼一起使用( getPolls () 除外)。 我認為問題來自 API。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM