componentDidMount(){
this.getedata();
}
componentDidUpdate() {
this.getedata();
}
解决在componentDidUpdate中不断setstate调用自身的死循环
shouldComponentUpdate(nextProps, nextState) {
return nextProps.match.params.id != this.props.match.params.id || nextState.newsdetails.news_id != this.state.newsdetails.news_id
}
getedata(){
post('/news/list',{
"page":1
}).then(res => {
this.setState({
newslist:res.List
},()=>{
console.log("新闻列表",this.state.newslist)
})
})
post('/news/details',{
"news_id":this.props.match.params.id*1
}).then(res => {
console.log("新闻详情",res)
this.setState({
newsdetails:res
},()=>{
console.log("新闻详情",this.state.newsdetails)
})
})
}
- 有参数则传参数,无参数则从url中获取
updata(id){
console.log("方法",id)
this.props.history.push(`/dynamic/news/${id}`)
this.getedata(id)
}
getedata(id) {
post('/news/list', {
"page": 1
}).then(res => {
this.setState({
newslist: res.List
})
})
post('/news/details', {
"news_id": id
}).then(res => {
// console.log("新闻详情", res)
this.setState({
id: res.news_id,
newsdetails: res,
detailstime: res.created_at.split(' ')
})
})
}
// 请求数据
componentDidMount() {
this.getedata(this.props.match.params.id * 1);
}
{
this.state.newslist.length > 0 && this.state.newslist.map((obj, index) => {
// console.log('11', index)
return <li key={index} className="main-right-show">
{/* to={`/dynamic/news/${obj.news_id}`} */}
·····················在这里调用updata方法并传参(当前点击对应页面的id)························
<div key={index} onClick={this.updata.bind(this,obj.news_id)}>
{/* 展示区内部标题栏 */}
<div className="main-right-show-title">
<span className="main-right-show-title-time">{obj.created_at}</span>
<div className="main-right-show-title-line"></div>
<span className="main-right-show-title-word">{obj.tittle}</span>
</div>
{/* 展示区内部新闻 */}
<div className="main-right-show-news" dangerouslySetInnerHTML={{ __html: decodeURI(obj.details).replace(/<[^>]+>/g, "") }}>
</div>
</div>
</li>
})
}