抱歉我的英语不好,英语不是我的第一语言。
嗨,我是新手反应JS,在下面的代码中一切正常但是当我点击logout handler它显示
” × TypeError:无法读取未定义的属性'replace' “
请告诉我如何在点击退出处理程序时重定向到登录页面
我尝试了所有可能性:
this.props.history.push( 'somepath') this.context.history.push( 'somepath') 但没有什么对我有用我研究了很多,但没有找到真正的答案。
import React,{Component} from 'react';
import {BrowserRouter,Link,Route} from 'react-router-dom';
import Contact from './contact';
class Home extends Component {
constructor(props) {
super(props)
}
logoutHandler =(e) => {
this.props.history.replace('/login')
}
render() {
return(
<BrowserRouter>
<div>
<header>
<Link to='/contact'>Contact</Link>
</header>
<div>
<Route path='/contact' Component={Contact}></Route>
</div>
<a href="#" onClick={e=>this.logoutHandler(e)}>Logout</a>
</div>
</BrowserRouter>
)
}
}
export default Home;`
答案 0 :(得分:0)
您应该使用this.props.history.push('/login')
。
您的错误原因是您没有使用HOC react路由器包装组件导出。
添加导入
import {withRouter} from 'react-router-dom';
并将组件导出包装为export default withRouter(Home);
。这样,历史记录将被注入您的Home组件。
答案 1 :(得分:0)
使用WithRouter
访问历史记录对象
import React,{Component} from 'react';
import { withRouter } from 'react-router'
import {BrowserRouter,Link,Route} from 'react-router-dom';
import Contact from './contact';
class Home extends Component {
constructor(props) {
super(props)
}
logoutHandler =(e) => {
this.props.history.push('/login')
}
render() {
return(
<BrowserRouter>
<div>
<header>
<Link to='/contact'>Contact</Link>
</header>
<div>
<Route path='/contact' Component={Contact}></Route>
</div>
<a href="#" onClick={e=>this.logoutHandler(e)}>Logout</a>
</div>
</BrowserRouter>
)
}
}
export default withRouter(Home);