在使用 this.props.history.push(’/singer/’+item.id)进行跳转的时候报错:
Cannot read property ‘push’ of undefined,因为之前都是这么跳转的没有报错,这次竟然报错了,很郁闷。
最简单直接在父组件加上history={ this.props.history }
例如: <SingerView singerList={ this.state.singerList } history={ this.props.history }/>
如果还不行,请继续往下看,那就和我的情况差不多了
首先介绍下项目结构,下面是歌手页面,有三个组件嵌套而成,我想做的是点击歌手名字的时候跳转到歌手详情页面。
最后查了资料才知道是因为我这个跳转方法是在子组件的子组件中进行的,所以报错了。
最终解决办法:
歌手名字组件(子组件的子组件)
import React , { Component } from 'react';
import './singerTel.less';
class singerTel extends Component{
constructor(props) {
super(props);
}
componentDidMount(){
}
selectSinger=(singer)=>{
this.props.selectSinger(singer) //组件传值
}
render(){
let singerObj = this.props.singerObj;
return(
<>
{
singerObj.items.map(( item , index )=>{
return <div className='singerList' key={ item.id } onClick={()=>{
//再点击的时候不进行跳转,把所需要传的值,传给其父组件,让其父组件进行处理、
this.selectSinger(item)
}}>
<span className='singerPicSpan'> <img src={ item.avatar } alt=""/></span>
<span> { item.name }</span>
</div>
})
}
</>
)
}
}
export default singerTel;
子组件(歌手列表发父组件)
import React , { Component } from 'react';
import SingerTel from '../../components/singerTel/singerTel'
import './singerView.less';
class singerView extends Component{
constructor(props){
super(props);
this.state={};
}
componentDidMount(){
console.log(this.props.singerList)
}
checkSinger=(singer)=>{
// 接收到子组件传过来的值以后进行页面跳转
this.props.history.push('/singerPage/'+singer.id);
}
render(){
let singerList = this.props.singerList;
return(
<ul className='singerCon'>
{
singerList.map((item,index)=>{
return <li key={ item+index }>
<h4>{ item.tittle }</h4>
// 再此接收子组件传过来的值
<SingerTel singerObj = { item } selectSinger = { this.checkSinger }/>
</li>
})
}
</ul>
)
}
}
export default singerView;
父组件
//在父组件加上 history={ this.props.history }
<SingerView singerList={ this.state.singerList } history={ this.props.history }/>
问题解决