问题
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 --
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- Here I have Question , 3 options how can I show to frontend
Error -
回答1:
There is two little mistakes in the code that you show us:
- the first One you imported
import Polls from "./polls";
and you call<Poll noStorage question={poll.question} answers={poll.options} onVote={handleVote}/>
just change Poll by Polls. const [pollAnswers, setPollAnswers] = useState([...answers]);
this didn't work because you need to pass a initial value for your state andanswer
is not yet initialize and accessible. just changeuseState([...answers]);
byuseState([]);
UPDATE:
you need to pass an array to answers props . 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...)
UPDATE
Your data object is not well formated to fit react-polls answers props. in the npmjs doc of react-polls we can see an example of options and it's an array of object like this:
[
{ 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()). I think the issue come from the API.
来源:https://stackoverflow.com/questions/65936091/fetching-data-from-api-in-react-poll