当我在主页面中获取数据时,一切都按我的要求工作,但是当我使用相同的代码在另一个文件夹中使用动态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 10:07:15
您的响应数据有时不会获取资源字段。
这就是为什么book.resources
可以是未定义(或) null的原因。
您可以很容易地使用可选的更改(?)
取代:
{
book.resources?.find(
({ type }) => type === 'application/epub+zip'
)?.uri || ''
}
发布于 2022-05-26 10:46:36
除了吴宇的回答外,当考虑如何呈现代码时,
首先只在页面加载时执行return
,然后才执行useEffect
,因为useEffect
依赖数组中没有值。
因此,在您的场景中,初始页面加载中有data = null。因此,当呈现下面的代码时,因为data = null data.results
不能使用Arrays.map()。
然后执行useEffect
,并在其中设置从API调用返回的值,并将该值设置为data。
为了避免呈现未定义的错误,您必须确保data.results
不等于空/未定义,并且在存在data.results
时呈现所需的内容。
你可以通过以下方式实现这一点。
undefined or null
时通过连接的对象访问值。当book.resources
等于空/未定义时,它不会给出上述错误。data.results
和book.resources
有值时才呈现,否则如下所示。
//此处有条件地检查是否存在data?.results值,如果存在,则呈现此值。{data?.results && data.results.map((图书,索引) => ( {book.title} /reader/${book.id}} passHref> ]) {/*,这里也有条件地检查book?.resources是否有值,如果存在,则呈现此值。*/} { book?.resources && book.resources.find( ({ type }) =>类型=== 'application/epub+zip‘).uri })}https://stackoverflow.com/questions/72396129
复制相似问题