我正在學習 React,但在從我的 API 獲取嵌套陣列時遇到問題。我正在嘗試將陣列呈現為按鈕。起初代碼有效,但在重繪 網頁時,我得到一個空白頁面,控制臺中出現此錯誤:“未捕獲的型別錯誤: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>
);
這是我的貓鼬模式
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" }
);
// 大菜鳥,感謝幫助
uj5u.com熱心網友回復:
您的初始狀態是錯誤的,因為空陣列[]沒有可以映射的屬性選項。而是嘗試:
const [item, setItem] = useState({options: []});
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/388523.html
標籤:javascript 数组 反应 猫鼬 拿来
