获取嵌套数组 React
Fetch nested array React
我正在学习 React,但在从 API 中获取嵌套数组时遇到问题。我正在尝试将数组呈现为按钮。起初代码有效但在刷新网页时我得到一个空白页面并且控制台中出现此错误:“Uncaught TypeError:item.options is undefined”。
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" }
);
// 大菜鸟,感谢帮助
您的初始状态是错误的,因为空数组 []
没有 属性 可以映射的选项。而是尝试:
const [item, setItem] = useState({options: []});
我正在学习 React,但在从 API 中获取嵌套数组时遇到问题。我正在尝试将数组呈现为按钮。起初代码有效但在刷新网页时我得到一个空白页面并且控制台中出现此错误:“Uncaught TypeError:item.options is undefined”。
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" }
);
// 大菜鸟,感谢帮助
您的初始状态是错误的,因为空数组 []
没有 属性 可以映射的选项。而是尝试:
const [item, setItem] = useState({options: []});