简体   繁体   English

在反应轮询中从 API 获取数据

[英]fetching data from API in react poll

I want to fetch data from API and show frontend using react but I am getting error from frontend side which is (TypeError: answers.map is not a function ) so how can I solve this error --我想从 API 获取数据并使用 React 显示前端,但我从前端收到错误(TypeError: answers.map is not a function )所以我该如何解决这个错误 -

MY CODE IS -我的代码是 -

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;

Data which I am getting from API is-我从 API 获得的数据是- 在此处输入图像描述 Here I have Question, 3 options how can I show to frontend在这里我有问题,3 个选项如何显示给前端

Error -错误 - 在此处输入图像描述

There is two little mistakes in the code that you show us:您向我们展示的代码中有两个小错误:

  1. the first One you imported import Polls from "./polls";您导入的第一个import Polls from "./polls"; and you call <Poll noStorage question={poll.question} answers={poll.options} onVote={handleVote}/> just change Poll by Polls.并且您调用<Poll noStorage question={poll.question} answers={poll.options} onVote={handleVote}/>只需更改 Poll by Polls。
  2. const [pollAnswers, setPollAnswers] = useState([...answers]); this didn't work because you need to pass a initial value for your state and answer is not yet initialize and accessible.这没有用,因为您需要为 state 传递一个初始值,而answer尚未初始化和可访问。 just change useState([...answers]);只需更改useState([...answers]); by useState([]);通过useState([]);
    UPDATE :更新
    you need to pass an array to answers props.您需要将数组传递给 answers 道具。 We can see in your console screenshot that the array of options has "none" as key so try this: <Poll noStorage question={poll.question} answers={poll.options.none} onVote={handleVote}/> ("none" is a strange key...)我们可以在您的控制台屏幕截图中看到,选项数组以“none”作为键,所以试试这个: <Poll noStorage question={poll.question} answers={poll.options.none} onVote={handleVote}/> ("无”是一个奇怪的键...)
    UPDATE更新
    Your data object is not well formated to fit react-polls answers props.您的数据 object 的格式不适合 react-polls answers 道具。 in the npmjs doc of react-polls we can see an example of options and it's an array of object like this:react-polls的 npmjs 文档中,我们可以看到一个选项示例,它是一个 object 的数组,如下所示:
[
  { option: 'Yes', votes: 8 },
  { option: 'No', votes: 2 }
]

so based on the data console log that you add in your question it should looks like this:因此,根据您在问题中添加的数据控制台日志,它应该如下所示:

[
  {
    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"
  }
]

see a sandBox here working with your code (except getPolls()).在此处查看一个沙盒与您的代码一起使用( getPolls () 除外)。 I think the issue come from the API.我认为问题来自 API。

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

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