[英]Cannot read properties of undefined (reading 'length') in codesandbox
const News = (props)=>{
const [articles, setArticles] = useState([])
const [loading, setLoading] = useState(true)
const [page, setPage] = useState(1)
const [totalResults, setTotalResults] = useState(0)
const capitalizeFirstLetter = (string) => {
return string.charAt(0).toUpperCase() + string.slice(1);
}
const updateNews = async ()=> {
props.setProgress(10);
const url = `https://newsapi.org/v2/top-headlines?country=${props.country}&category=${props.category}&apiKey=${props.apiKey}&page=${page}&pageSize=${props.pageSize}`;
setLoading(true)
let data = await fetch(url);
props.setProgress(30);
let parsedData = await data.json()
props.setProgress(70);
setArticles(parsedData.articles)
setTotalResults(parsedData.totalResults)
setLoading(false)
props.setProgress(100);
}
useEffect(() => {
document.title = `${capitalizeFirstLetter(props.category)} - NewsPanda`;
updateNews();
// eslint-disable-next-line
}, [])
const fetchMoreData = async () => {
const url = `https://newsapi.org/v2/top-headlines?country=${props.country}&category=${props.category}&apiKey=${props.apiKey}&page=${page+1}&pageSize=${props.pageSize}`;
setPage(page+1)
let data = await fetch(url);
let parsedData = await data.json()
setArticles(articles.concat(parsedData.articles))`enter code here`
setTotalResults(parsedData.totalResults)
};
return (
<>
<h1 className="text-center" style={{ margin: '35px 0px', marginTop: '90px' }}>NewsPanda - Top {capitalizeFirstLetter(props.category)} Headlines</h1>
{loading && <Spinner />}
<InfiniteScroll
dataLength={articles.length} /////here i'm getting this error/////
next={fetchMoreData}
hasMore={articles.length !== totalResults}
loader={<Spinner/>}
>
<div className="container">
<div className="row">
{articles.map((element) => {
return <div className="col-md-4" key={element.url}>
<NewsItem title={element.title ? element.title : ""} description={element.description ? element.description : ""} imageUrl={element.urlToImage} newsUrl={element.url} author={element.author} date={element.publishedAt} source={element.source.name} />
</div>
})}
</div>
</div>
</InfiniteScroll>
</>
)
}
While forking my code from github to codesandbox, it is showing the error "Cannot read properties of undefined (reading 'length')" in codesandbox.在将我的代码从 github 分叉到codesandbox 时,它在codesandbox 中显示错误“无法读取未定义的属性(读取'长度')”。 But i have defined articles above.但我在上面定义了文章。
I really don't know what is happening here.我真的不知道这里发生了什么。 Anyone got a solution for this?有人对此有解决方案吗?
It is showing an error at line dataLength = {articles.length};
它在dataLength = {articles.length};
You are receiving an error as a response from newsapi.org
您收到来自newsapi.org
的错误响应
{
code: "corsNotAllowed"
message: "Requests from the browser are not allowed on the Developer
plan, except from localhost."
status: "error"
}
Your News
component is expecting articles
to be an array and breaks if it is not.您的News
组件期望articles
是一个数组,如果不是则中断。 You should only add parsedData.articles
into state conditionally, or else it could be undefined
.您应该只将parsedData.articles
有条件地添加到状态中,否则它可能是undefined
。
const updateNews = async () => {
setError(null)
props.setProgress(10);
const url = `https://newsapi.org/v2/top-headlines?country=${props.country}&category=${props.category}&apiKey=${props.apiKey}&page=${page}&pageSize=${props.pageSize}`;
setLoading(true);
let data = await fetch(url);
props.setProgress(30);
let parsedData = await data.json();
if (parsedData.status !== 'error') {
props.setProgress(70);
setArticles(parsedData.articles);
setTotalResults(parsedData.totalResults);
props.setProgress(100);
} else {
props.setProgress(0);
setError('Something went wrong')
}
setLoading(false);
};
In code an object has to be defined.在代码中必须定义一个对象。
In your code articles probably not defined thus length cannot be resolved.在您的代码中可能未定义文章,因此无法解决长度问题。
{ articles.length ...
Two things you need to do is see that articles indeed properly set as an array.您需要做的两件事是查看文章确实正确设置为数组。 And you can add a validation for articles variable您可以为文章变量添加验证
{ articles?.length
The validation can lead to other errors so you better validate your variables as early in your code as you can.验证可能会导致其他错误,因此您最好尽早在代码中验证变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.