[英]Fetch nested array React
I am learning React but having problems with fetching nested arrays from my API.我正在学习 React,但在从我的 API 获取嵌套的 arrays 时遇到问题。 I am trying to render an array as buttons.
我正在尝试将数组呈现为按钮。 At first the code works but on refreshing the webpage I get a blank page and this error in the console: "Uncaught TypeError: item.options is undefined".
起初代码有效,但在刷新网页时,我得到一个空白页面,并且控制台中出现此错误:“未捕获的 TypeError:item.options 未定义”。
let { id } = useParams();
//console.log(id);
//kalla på fetchItem
useEffect(() => {
getMovie();
}, []);
//hämta enskild
const [item, setItem] = useState([]);
const getMovie = async () => {
const fetchItem = await fetch(`http://localhost:5000/api/movies/id=${id}`);
const item = await fetchItem.json();
setItem(item);
console.log(item);
};
//hämta, map för att det är array
return (
<div className="App">
<h1>Hello</h1>
<h2>Question: {item.description}</h2>
{item.options.map((c) => (
<button key={c.text}>{c.text}</button>
))}
</div>
);
This is my mongoose schema这是我的 mongoose 架构
const MovieSchema = mongoose.Schema(
{
category: { type: String, required: true },
description: { type: String, required: true },
image: {
type: String,
required: false,
},
options: [
{
text: {
type: String,
required: true,
},
is_correct: {
type: Boolean,
required: true,
default: false,
},
image: {
type: String,
required: false,
},
},
],
},
{ collection: "movies" }
);
// Big noob, thanks for helping // 大菜鸟,感谢帮助
Your initial state is wrong, as the empty array []
has no property options that could be mapped.您最初的 state 是错误的,因为空数组
[]
没有可以映射的属性选项。 Instead try:而是尝试:
const [item, setItem] = useState({options: []});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.