0
点赞
收藏
分享

微信扫一扫

react中路由重定向


react中路由重定向

​​react路由重定向官方文档说明​​​ render 属性:是一个函数prop,用于指定要渲染的内容
Redirect 组件用于实现路由重定向,to 属性指定要跳转到的路由地址

<Route exact path="/home" component={Index} />

<Route exact path="/" render={() => <Redirect to="/home" />} />

如下代码逻辑说明:
当进来到页面中是默认路由的时候,就进行一个路由的重定向,重定向到 /home路由
路由是home了那就匹配到Hoem组件。

import { BrowserRouter as Router, Route, Link,Redirect} from "react-router-dom";
import Home from "./pages/Home";
import CityList from "./pages/CityList";
function App() {
return (
<Router>
<div className="App">
{/* 默认路由,实现路由的重定向 */}
<Route exact path="/" render={ ()=> <Redirect to="/home"/>}></Route>
<Route path="/home" component={Home}></Route>
<Route path="/citylist" component={CityList}></Route>
</div>
</Router>
);
}

export default App;

Home组件代码,看路由跳转模块即可。路由是/home,那就接着匹配显示的组件

import React from "react";
import "./index.css";
import { Route } from "react-router-dom";
import { TabBar } from "antd-mobile";
// 组件
import Index from "../Index/index";
import List from "../List/index";
import News from "../News/index";
import My from "../My/index";

// 导航栏数据
const tabItems = [
{
title: "首页",
icon: "icon-ind",
path: "/home",
},
{
title: "找房",
icon: "icon-findHouse",
path: "/home/list",
},
{
title: "咨询",
icon: "icon-infom",
path: "/home/news",
},
{
title: "我的",
icon: "icon-my",
path: "/home/my",
},
];

class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedTab: this.props.location.pathname,
};
}
renderTabItem = () => {
return tabItems.map((item) => (
<TabBar.Item
title={item.title}
key={item.title}
icon={<i className={"iconfont " + item.icon} />}
selectedIcon={<i className={`iconfont ${item.icon}`} />}
selected={this.state.selectedTab === item.path}
onPress={() => {
this.setState({
selectedTab: item.path,
});
this.props.history.push(item.path);
}}
></TabBar.Item>
));
};

render() {
return (
<div className="home">
{/* 当路由是/home时,匹配到了home组件,home组件里又匹配到了下面的路由,故展示 */}
<Route exact path="/home" component={Index}></Route>
<Route path="/home/list" component={List}></Route>
<Route path="/home/news" component={News}></Route>
<Route path="/home/my" component={My}></Route>
<TabBar tintColor="#21b97a" barTintColor="white" noRenderContent>
{this.renderTabItem()}
</TabBar>
</div>
);
}
}
export default Home;


举报

相关推荐

0 条评论