当我单击下一个按钮时,我收到**“News.js:16 Uncaught(in Promise)TypeError:无法读取未定义的属性(读取“状态”)”**的错误。 处理下一个单击按钮事件的 URL 发生错误。 它是一个新闻应用程序,在下一个按钮中我想显示新闻的第 2 页 新闻组件代码
import React, { Component } from "react";
import Newsitem from "./Newsitem";
export class News extends Component {
constructor(props) {
super(props);
/* this.handleNextClick = this.handleNextClick.bind(this)
this.handlePreviousClick = this.handlePreviousClick.bind(this) */
this.state = {
articles: [],
loading: false,
page:1
};
}
async componentDidMount(){
let url = `https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=b3087d8cbca244c887caeb51aacfab68&page=${this.page.state+1}&pagesize=${this.props.pagesize}`;
let data = await fetch(url);
let parsedData = await data.json();
console.log(parsedData);
this.setState({articles: parsedData.articles,
totalresults:parsedData.totalresults });
}
handleNextClick = async ()=>{
console.log("next")
if(!this.page.state + 1 > Math.ceil(this.state.totalresults/this.props.pagesize)){
let url = `https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=b3087d8cbca244c887caeb51aacfab68&page=${this.page.state+1}&pagesize=${this.props.pagesize}`;
let data = await fetch(url);
let parsedData = await data.json();
console.log(parsedData);
this.setState({page : this.state.page + 1 ,
articles : parsedData.articles });
}
}
handlePreviousClick = async()=>{
console.log("Previous")
let url = `https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=b3087d8cbca244c887caeb51aacfab68&page=${this.page.state+1}&pagesize=${this.props.pagesize}`;
let data = await fetch(url);
let parsedData = await data.json()
console.log(parsedData);
this.setState({page: this.state.page - 1,
articles: parsedData.articles})
}
render() {
return (
<div className="container my-4 ">
<h1 className="text-center">NewsMonkey - TOP Headlines</h1>
<div className="row">
{this.state.articles.map((element)=>{
return <div className="col-md-4" key={element.url}>
<Newsitem title = {element.title?element.title.slice(0,40):""} description={element.description?element.description.slice(0,80):""} imgUrl={element.urlToImage} newsUrl = {element.url}/>
</div>
})}
</div>
<div className="container d-flex justify-content-between" >
<button type="button" disabled={this.state.page<=1} className="btn btn-dark" onClick={this.handlePreviousClick}> ← Previous</button>
<button type="button" disabled={this.state.page+1>Math.ceil(this.state.totalresults/this.props.pagesize)}className="btn btn-dark" onClick={this.handleNextClick}>Next →</button>
</div>
</div>
);
}
}
我尝试了绑定方法,但它对我的问题不起作用
错误来自第16行的
this.page.state
,其他有此代码的链接也会发出该错误。
尝试将其替换为
this.state.page
请务必小心,不要像在这里通过提问那样在线分享 ApiKey。