当我在主页面中获取数据时,一切都按我的要求工作,但是当我使用相同的代码在另一个文件夹中使用动态url时,当我试图在数组上使用方法时,会出现一个错误。当我console.log获取数据时,得到的数组与主页中的数组相同。
当我删除链接而只想看到book.title时,它可以工作。但是当我想从资源中获取数据时,我遇到了错误。
mainpage.js
const [data, setData] = useState(null);
const [isLoading, setLoading] = useState(false);
useEffect(() => {
setLoading(true);
fetch('https://gnikdroy.pythonanywhere.com/api/book')
.then((res) => res.json())
.then((data) => {
setData(data);
setLoading(false);
});
}, []);
return(
<div>
{data.results.map((book, index) => (
<div key={index}>
<h1>{book.title}</h1>
<Link href={`/reader/${book.id}`} passHref>
<h2>
{
book.resources.find(
({ type }) => type === 'application/epub+zip'
).uri
}
</h2>
</Link>
</div>
))}
</div>
)searchPage.js
const router = useRouter();
const { name } = router.query;
const [data, setData] = useState(null);
const [loading, setLoading] = useState(false);
useEffect(() => {
setLoading(true);
fetch(`https://gnikdroy.pythonanywhere.com/api/book/?search=${name}`)
.then((res) => res.json())
.then((data) => {
setData(data);
setLoading(false);
console.log(data);
});
}, []);
return(
<div>
{data.results.map((book, index) => (
<div key={index}>
<h1>{book.title}</h1>
<Link href={`/reader/${book.id}`} passHref>
<h2>
{
book.resources.find(
({ type }) => type === 'application/epub+zip'
).uri
}
</h2>
</Link>
</div>
))}
</div>
)

我的console.log内置searchPage.js

发布于 2022-05-26 18:07:15
您的响应数据有时不会获取资源字段。
这就是为什么book.resources可以是未定义(或) null的原因。
您可以很容易地使用可选的更改(?)
取代:
{
book.resources?.find(
({ type }) => type === 'application/epub+zip'
)?.uri || ''
}https://stackoverflow.com/questions/72396129
复制相似问题