![](/img/trans.png)
[英]CORS Error when fetching data from Zoho API on React frontend
[英]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;
您向我們展示的代碼中有兩個小錯誤:
import Polls from "./polls";
並且您調用<Poll noStorage question={poll.question} answers={poll.options} onVote={handleVote}/>
只需更改 Poll by Polls。const [pollAnswers, setPollAnswers] = useState([...answers]);
這沒有用,因為您需要為 state 傳遞一個初始值,而answer
尚未初始化和可訪問。 只需更改useState([...answers]);
通過useState([]);
<Poll noStorage question={poll.question} answers={poll.options.none} onVote={handleVote}/>
("無”是一個奇怪的鍵...)[
{ 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.