當我在我的主頁中獲取資料時,一切都按我的意愿作業,但是當我使用相同的代碼但使用動態 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 console.log中獲取
uj5u.com熱心網友回復:
您的回應資料有時沒有獲取資源欄位。
這就是為什么book.resources可以未定義(或)為空。
您可以輕松使用可選更改(?。)
代替:
{
book.resources?.find(
({ type }) => type === 'application/epub zip'
)?.uri || ''
}
uj5u.com熱心網友回復:
除了 Wu Woo 的回答,當考慮如何 React 呈現您的代碼時,
First 將執行returnand 然后useEffect僅在頁面加載中執行,因為您在useEffectDependency 陣列中沒有值。
因此,在您的場景中,您在初始頁面加載中有data = null 。所以當在代碼下面渲染時,由于data = null data.results不能使用 Arrays.map()。
然后將執行useEffect并在其中設定從 API 呼叫回傳的值并將該值設定為資料。
為避免呈現未定義的錯誤,您必須確保data.results不等于 null/undefined 以及何時data.results呈現您想要的內容。
您可以通過以下方式實作這一目標。
可選的鏈接運算子 (?.) 作為 Wu Woo 的答案,當參考或函式可能是 時,它簡化了通過連接物件訪問值
undefined or null。book.resources那么當等于 null/undefined時它不會給出上述錯誤。僅在有值時才渲染
data.results,book.resources否則不如下所示。// Here conditionally check whether there is value for data?.results and if so render this. {data?.results && data.results.map((book, index) => ( <div key={index}> <h1>{book.title}</h1> <Link href={`/reader/${book.id}`} passHref> <h2> {/* Here also conditionally check whether there is value for book?.resources and if so render this. */} { book?.resources && book.resources.find( ({ type }) => type === 'application/epub zip' ).uri } </h2> </Link> </div> ))}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/481226.html
標籤:javascript 数组 下一个.js 获取 API
上一篇:如何比較物件陣列中的物件值?
下一篇:用布林值測驗回圈
