新建一个Home组件用于重定向:
import React, { Component } from 'react';
//要求进入Index就重定向到Home
class Home extends Component {
constructor(props) {
super(props);
this.state = { }
}
render() {
return ( <h2>我是Home组件-Redirect</h2> );
}
}
export default Home;
假设我们要求进入Index页面时必须重定向到Home页面。以下我们使用比较常用以及重要的两种重定向方式来实现,一种方式是使用标签进行重定向,另一种方式是编程进行重定向。
在AppRouter.js中配置一下Home页面的路由:
<Route path="/home/" component={Home}/>
标签重定向
标签重定向不适用于复杂场景。
在Index.js中引入Redirect:
import {Link,Redirect} from 'react-router-dom';
render函数中加入Redirect标签进行重定向:
render() {
return (
<div>
<Redirect to="/home/"/>
<div>Juan.com</div>
<ul>
{
this.state.list.map((item, index) => {
return (
<li key={index + item}>
<Link to={'/list/'+item.cid}>
{item.title}
</Link>
</li>
)
})
}
</ul>
</div>
);
}
实现效果如下,输入Index地址直接重定向到Home页面:
编程重定向
编程重定向非常简单,适用于有判断的情况,例如登录。首先注释掉之前的Redirect标签,在Index组件的constructor函数中加入以下代码即可,实现效果同上:
this.props.history.push("/home/");
完整代码
Index.js:
import React, { Component } from 'react';
import {Link,Redirect} from 'react-router-dom';
class Index extends Component {
constructor(props) {
super(props);
this.state = {
list: [
{
cid: 123,
title: '我的个人博客-1'
},
{
cid: 456,
title: '我的个人博客-2'
},
{
cid: 789,
title: '我的个人博客-3'
},
]
}
this.props.history.push("/home/");
}
render() {
return (
<div>
{/* <Redirect to="/home/"/> */}
<div>Juan.com</div>
<ul>
{
this.state.list.map((item, index) => {
return (
<li key={index + item}>
<Link to={'/list/'+item.cid}>
{item.title}
</Link>
</li>
)
})
}
</ul>
</div>
);
}
}
export default Index;
AppRouter.js:
import React from 'react';
import { BrowserRouter as Router,Route,Link } from 'react-router-dom';
import Index from './Pages/Index';
import List from './Pages/List';
import Home from './Pages/Home';
function AppRouter(){
return (
<Router>
<ul>
<li><Link to="/">首页</Link></li>
<li><Link to="/list/123">列表</Link></li>
</ul>
{/* exact表示精确匹配 */}
<Route path="/" exact component={Index}/>
<Route path="/list/:id" component={List}/>
<Route path="/home/" component={Home}/>
</Router>
)
}
export default AppRouter;