我想从API获取数据,并使用react显示前端,但我从前端端得到错误,这是(TypeError:答案)。map不是一个函数)那么我该如何解决这个错误——
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
return (
<div className="">
<div className="container">
<h1 className="blog_heading">Poll's of the Day</h1>
<div className="row">
{polls.reverse().map((poll, index) => (
<div className="col-lg-4 col-12" key={index}>
<Poll question={poll.question} answers={poll.options} />
</div>
))}
</div>
</div>
</div>
);
};
export default MainPoll;
我从API获得的数据是-输入图片描述
这里我有问题,3个选项,我如何显示到前端
错误-输入图像描述
问题是:
字段options
从API是一个对象,我看到。
但是Poll组件试图与它交互,就像它是一个数组:answers.map(answer => answer.option)
正如我从文档中看到的,数据格式应该是:
[
{ option: 'Yes', votes: 8 },
{ option: 'No', votes: 2 }
]
更新:您可以使用类似的代码片段将数据转换为所需的格式。
data.map(answer => {
return {
question: answer.question,
answers: Object.keys(answer.options).map(key => {return {option: key, votes: 0}})
}
})