【发布时间】:2021-01-21 07:38:48
【问题描述】:
大家好,我是尝试构建动漫 WEB APP 的新手 问题是当我尝试获取新数据并将新数据与我所在州的 prev 数据一起存储时 但在它存储之前 setIsLoading 变为 true 并且所有应用程序都因问题而崩溃
“类型错误:无法读取未定义的属性‘canonicalTitle’”
这是我的代码:
import React,{useState, useEffect} from 'react'
import Card from './cards'
function Movies(){
const [data , setData] = useState([])
const [isLoading , setIsLoading] = useState(true)
const [value , SetValue] = useState('')
const [isBottom, setIsBottom] = useState(false);
const [page , setPage] = useState(0)
const style={
fontSize: "2rem",
textAlign: "center" ,
borderRadius:"25px",
padding : "0% 20%" ,
marginLeft:"19%"
}
const LISTED_API= `https://kitsu.io/api/edge/anime?page[limit]=20&page[offset]=${page}`
const SEARCH_API = `https://kitsu.io/api/edge/anime?filter[text]=$`
useEffect(()=>{
readData(LISTED_API)
},[page])
//FEATCHING API DATA , SET DATA , Set Loading //
const readData = (API)=> {
setIsLoading(true)
fetch(API)
.then((res)=>res.json())
.then((data)=>{
setData(data.data)
})
.then(setIsLoading(false))
}
//search handel//
function handelChange(e){
const searchValue = e.target.value
SetValue( searchValue)
readData(SEARCH_API+searchValue)
if (!searchValue){
readData(LISTED_API)
}
}
//Listen to Scroll //
useEffect(() => {
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
}, []);
//Set True if reach Buttom//
function handleScroll(){
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
setIsBottom(true)
}else{
setIsBottom(false)
}
}
useEffect(() => {
if (isBottom) {
setPage((prev)=>prev + 20)
setData((prev)=>{
return [...prev ,[data]]
})
}
}, [isBottom]);
return(<div>
<header>
<input style={style} type="text" name="name" placeholder="Search..." onChange={(e)=>{handelChange(e)}} />
<h1>{value}</h1>
</header>
<div className="grid-container">
{isLoading ? 'Loading...' : data.map(e=>
<Card
key={e.id}
id={e.id}
name={e.attributes.canonicalTitle}
img={e.attributes.posterImage.small}
description={e.attributes.description}/>
)}
</div>
</div>)
}
export default Movies
【问题讨论】:
标签: javascript reactjs api react-hooks fetch