路由配置
BrowserRouter:history路由
HashRouter:hash路由
Router:的history是必需的props
Switch:表示只渲染第一个与当前地址匹配的
Prompt:防止转换 <Prompt shen={true} message="确定离开此页面?" ></Prompt>
Route 渲染组件的方式
- Route的props path为路径,component为路径对应的页面,Route 是 React Router中用于配置路由信息的组件,每当有一个组件需要根据 URL 决定是否渲染时,就需要创建一个 Route
- component 的值是一个组件,当 URL 和 Route 匹配时,Component属性定义的组件就会被渲染
- exact 属性表示精确匹配
安装路由
npm install react-router-dom --save
创建路由文件
/src/router/index.js
//导入组件Index,Page1 //需要自己先创建好组件
import Index from '../pages/index/index';
import Page1 from '../pages/page1/index';
import PageNotFound from '../pages/PageNotFound/index';
import React,{Component} from 'react';
import {
HashRouter as Router, //BrowserRouter(history路由) HashRouter(hash路由)
Switch,
Route,
Link,
Redirect
} from "react-router-dom";
import { createHashHistory } from "history";
const history = createHashHistory();
let routes = [
{
path: "/",
component: Index,
exact: true,
},
{
path: "/page1",
component: Page1,
exact: true,
},
{
path: "/404",
component: PageNotFound,
exact: true,
}
]
class Routes extends Component {
render(){
return (
<Router history={history}>
<div>
<div>
<header>
<Link to="/">index</Link>|
<Link to="/page1">page1</Link>
</header>
</div>
<Switch>
{/*
当访问到以/index开头的页面时,走App组件渲染 App页面元素也会显示 配置后需要在app组件中配置以下map渲染的过程
*/}
<Route path="/index" render={(routeProps)=><App {...routeProps} />} />
{
routes.map((route,key)=>{
if(route.exact){
return <Route key={key} exact path={route.path} component={route.component} />
}else{
return <Route key={key} path={route.path} component={route.component} />
}
})
}
{/*
Redirect必须放Switch里的最后一行
如果上面的路由都匹配不到时,跳转到"/"页面(即渲染index组件)
*/}
<Redirect from="/*" to="/404" />
</Switch>
</div>
</Router>
)
}
}
export default Routes;
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import reportWebVitals from './reportWebVitals';
import RouterConfig from './router/index.js'; //引入路由文件
ReactDOM.render(
<React.StrictMode>
<RouterConfig />
</React.StrictMode>,
document.getElementById('root')
);
创建组件
例:src/pages/index/index.js
function Index() {
return (
<div className="Index">
Index
</div>
);
}
export default Index;
跳转路由
js跳转路由
this.props.history.push('/login')
标签跳转路由
<Link to="/page1">page1</Link>
返回上一页(1)
window.history.back(-1);
返回上一页(2)
// 如果使用hashHistory
import creatHistory from 'history/createHashHistory'
//(两个选一个)
// 如果使用createBrowserHistory
import creatHistory from 'history/createBrowserHistory'
const history = creatHistory();
history.goBack();