Cannot read property ‘push’ of undefined

在使用 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 }/>

问题解决

  • 5
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值