我正在使用react-router v4
,但我无法从登录组件重定向到主页(索引(,这是我的代码示例,带有重定向按钮。
登录.js
constructor(props)
{
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(e) {
e.preventDefault();
this.context.router.history.push('/home');
}
<button onClick={(e) => this.handleClick(e)}>
Navigate
</button>
索引.js
ReactDOM.render((
<Provider store={store}>
<Router history={hashHistory}>
<MuiThemeProvider>
<div>
<Login>
<div>
<SearchBar/>
<MainMenu/>
</div>
<Switch>
<Route path="/home" component={Home}/>
<Route path="/calendar" component={Calendar}/>
<Route path="/about" component={About}/>
</Switch>
<Footer/>
</Login>
</div>
</MuiThemeProvider>
</Router>
</Provider>
),document.getElementById('content'));
解决方案 1:使用链接
对于简单的解决方案,您可以使用react-router-dom
中的Link
组件,而不是Login.js
中的按钮。有一些方法可以在 JS 中更改路由,但这似乎更容易。
您需要先导入登录:
import {Link} from 'react-router-dom';
然后将您的<button>
和handleClick()
替换为以下内容:
<span className="someclass">
<Link to="/home" />Navigate</Link>
</span>
解决方案 2:使用重定向
<Redirect exact from='/' to='/home' />
附言在当前的代码设置中,您还可以尝试在handleClick()
中使用this.props.history.push('/home')
而不是this.context.router.history.push('/home')
。