【问题标题】:Uncaught TypeError: Cannot read property 'push' of undefined React js未捕获的类型错误:无法读取未定义的 React js 的属性“推送”
【发布时间】:2020-08-23 21:02:32
【问题描述】:

我正在开发 React 应用程序。我在其他组件的子组件中使用 Header.js 组件。 当我单击链接时,它不会重定向到其他组件,它会显示在错误消息之后。

未捕获的类型错误:无法读取未定义的属性“推送”

使用“react”的版本:“^16.12.0”,“react-router-dom”:“^5.1.2”,

从堆栈溢出中搜索了很多,但没有人在工作。请帮助

Header.js

    import React from 'react';
import axios from 'axios';
import { history } from 'react-router-dom';
import { withRouter } from 'react-router-dom';
//import { useHistory } from "react-router-dom";--> Not Working

class Header extends React.Component {    

constructor(props) {
    super(props)
    this.state = {
        Search: '',
        guid:'',
        activeOption: 0,
        filteredOptions: [],
        showOptions: false,
        userInput: ''
    }
    this.onChangeSearch = this.onChangeSearch.bind(this);
    this.routeChange = this.routeChange.bind(this);
    this.Redirect = this.Redirect.bind(this);
}

onChangeSearch= (e) => {
    this.setState({ Search: e.target.value })       

     const obj = {
        User_Guiid:guid,
        Search:this.state.Search
     }
     if(this.state.Search!="")
     axios.post('http://localhost:xxxx/Api/Authenticate/Searchuser', obj }).then(response => {
        // console.log(response.data)  
         if(response.status=="200")
         {
            this.setState({
                filteredOptions:response.data
            })
            console.log(this.state.filteredOptions)
         }
      })
      .catch((error) =>{
        alert("Your Session time expired.Please Login Again."+error);
        this.props.history.push('/');   --> Redirect Working
     });

 e.preventDefault();
}
handleClick = (e) => {

    e.preventDefault();
    var guid= localStorage.getItem('Guiid');
    console.log(guid);
  //  this.props.history.push('/')
    this.props.history.push('/Profile/'+guid);--> Redirect Not Working

}
routeChange() {
    var guid= localStorage.getItem('Guiid');
    this.props.history.push('/Profile/'+guid);--> Redirect Not Working

  }
  Redirect(){
    var guid= localStorage.getItem('Guiid');
    this.props.history.push('/dashboard/'+guid);--> Redirect Not Working

  }
  Follow(e,guid){
    this.props.history.push('/follow/'+guid);--> Redirect Not Working
  }
  Clear(){
    this.setState({ Search: ''})
    window.location.reload();
  }
  Follows(e,guid){
  //const history = useHistory();
    console.log(guid)
    var id= localStorage.getItem('Guiid');   
    if(guid==id)
    {           
     //history.push('/follow/'+guid) --> Redirect Not Working;
      this.props.history.push('/follow/'+guid);--> Redirect Not Working
    }else{
     //history.push('/follow/'+id) --> Redirect Not Working;
      this.props.history.push('/follow/'+id);--> Redirect Not Working
    }

 }

render() {

    return (


        <nav className="NXc7H jLuN9">
            <div className="XajnB"></div>
            <div>
                <div className="_8MQSO  Cx7Bp">
                    <div className="_lz6s  ">
                        <div className="MWDvN  ">
                            <div className="oJZym">
                                <a href='' onClick={() => this.Redirect()}>
                                    <div className="   Igw0E   rBNOH    eGOV_   ybXk5    _4EzTm   ">

                                        <div className="SvO5t"></div>
                                        <div className="cq2ai">
                                            <img alt="" className="s4Iyt" src={Logo} />
                                        </div>
                                    </div>
                                </a>
                            </div>

                            <div className="LWmhU _0aCwM">
                                <input className="XTCLo x3qfX " type="text" autoCapitalize="none" placeholder="Search" value={this.state.Search} onChange={this.onChangeSearch} />
                                <span className="mlrQa coreSpriteSearchIcon sprite_search"></span>
                                {                  
                                     this.state.filteredOptions.map((user)=>{                    
                                  return (                       
                                   user.length != 0?
                                <div className="jLwSh" role="dialog"></div>
                                :null
                                )
                             })
                          }  
                                <div className="kbKz8">

                                 <div className="VR6_Q"></div>
                                  <div className="drKGC">
                                  {                  
                                     this.state.filteredOptions.map((user)=>{                    
                                  return (                       
                                   user.length != 0?
                                    <div className="fuqBx">
                                      <a className="yCE8d  " href="" onClick={(e) => this.Follows(e,user.User_Guiid)}>
                                       <div className="z556c">
                                         <div className="RR-M-  g9vPa" role="button" tabindex="0">
                                           <canvas className="CfWVH" height="42" width="42" style={{position: 'absolute', top: '-5px', left: '-5px', width: '42px', height: '42px'}}></canvas>
                                           <span className="_2dbep " role="link" tabindex="0" style={{width: '32px', height: '32px'}}>
                                           <img alt="" className="_6q-tv" src={require("../../img/Profile/"+user.UserImage)}/>
                                           </span>
                                          </div>
                                            <div className="_2_M76">
                                              <div className="uyeeR">
                                                 <span className="Ap253">{user.Username}</span>
                                                 <div className="JbY-k coreSpriteVerifiedBadgeSmall"></div></div>
                                                 <span className="Fy4o8">{user.Fullname}</span>
                                              </div>
                                        </div>
                                        </a>
                                    </div>
                                      :null
                                     )
                                  })
                               }  
                                </div>

                                </div>


                        </div>
                    </div>
                </div>
            </div>
        </nav>
    )
}
}
export default Header

【问题讨论】:

    标签: reactjs react-native react-redux react-router


    【解决方案1】:

    有两种调用历史推送的方法。

    1. 第一个带有 HOC 的路由器

    所以最后你应该把它包装起来。然后你可以使用像this.props.history.push()这样的推送方法

    export default withRouter(Header)
    
    1. 第二个是在 Hooks 的帮助下。我知道你应该使用功能组件来调用钩子,所以你应该稍微重写你的代码。我觉得这个方法写起来容易很多。您应该导入import { useHistory } from 'react-router-dom',然后将其称为const history = useHistory()。所以你可以调用像history.push() 这样的 push 方法,而不是用 withRouter 包装你的组件

    【讨论】:

      【解决方案2】:

      将组件包装在 react-route-dom 提供的 withRouter HOC 中。

      import React from 'react';
      import axios from 'axios';
      import { history } from 'react-router-dom';
      import { withRouter } from 'react-router-dom';
      import { useHistory, withRouter } from "react-router-dom";
      ....
      ....
      ..
      export default withRouter(Header)
      

      withRouter 是一个高阶组件,它会在渲染时将最近路由的匹配、当前位置和历史道具传递给被包装的组件。只需将组件连接到路由器即可。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-19
        • 2017-08-12
        • 2020-07-25
        • 1970-01-01
        • 2023-01-26
        • 2015-10-22
        • 2015-10-20
        相关资源
        最近更新 更多