嗨,我是React js的新手,我正在构建一个全堆栈的react应用程序。我在登录过程中使用Auth文件检查身份验证状态,我调用登录功能,在注销时间中,我像auth.js file。中那样调用注销功能。但是当我调用注销功能时,我收到“ TypeError:_this2.props.history未定义”错误。请帮我哪里错
class Auth {
constructor() {
this.authenticated = '';
}
login(cb) {
this.authenticated = true;
cb();
console.log("login status"+this.authenticated)
}
logout(cb) {
this.authenticated = false;
cb();
console.log("LOGOUT status"+this.authenticated)
}
isAuthenticated() {
console.log("check status"+this.authenticated)
return this.authenticated;
}
}
export default new Auth();
import React from 'react'
import zenologo from './images/zenologo.png'
import { Link } from 'react-router-dom'
import Auth from "./Auth";
import API from './api'
class Header extends React.Component {
constructor(props){
super(props)
this.state = {
admin : JSON.parse(localStorage.getItem('adminProfile'))
}
this.handleLogout = this.handleLogout.bind(this);
}
handleLogout() {
localStorage.removeItem('adminProfile')
localStorage.removeItem('access_token')
localStorage.removeItem('user')
localStorage.removeItem('itemDetails')
localStorage.removeItem('query')
Auth.logout(() => {
this.props.history.push('/admin/login')
});
}
render(){
return <header className="header">
<div class="container-fluid">
<nav>
<div className="dashboard_logoarea text-center">
<a href="#" className="menu_bar"><i className="fa fa-bars" aria-hidden="true"></i></a>
<a href="#"><img src={zenologo} alt="" /></a>
</div>
<div className="right_loggedarea">
<ul>
<li className="dropdown">
<a href="#" className="dropdown-toggle" role="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><img className="img-circle" style={{width:30,height:30}} src={API.getBaseImageURL()+'/'+this.state.admin.profileImage+"?"+new Date().getTime()} alt="" />My Account
<i className="fa fa-sort-desc" aria-hidden="true"></i>
</a>
<div className="dropdown-menu" aria-labelledby="dropdownMenuButton">
<Link to='/admin/profile'><i className="fa fa-user" aria-hidden="true"></i>My Profile</Link>
<Link to='/admin/edit_profile'><i className="fa fa-edit" aria-hidden="true"></i>Edit Profile</Link>
<a onClick={this.handleLogout}><i className="fa fa-power-off" aria-hidden="true"></i>Logout</a>
</div>
</li>
</ul>
</div>
</nav>
</div>
</header>;
}
}
export default Header
答案 0 :(得分:0)
您需要从withRouter
导入react-router-dom
,然后将其与export
这样的export default withRouter(Header);
答案 1 :(得分:0)
使用npm安装历史记录库摆脱使用this.props.history 我认为这可能会对您有所帮助https://www.npmjs.com/package/history