路由配置
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跳轉路由
标簽跳轉路由
傳回上一頁(1)
傳回上一頁(2)
// 如果使用hashHistory
import creatHistory from 'history/createHashHistory'
//(兩個選一個)
// 如果使用createBrowserHistory
import creatHistory from 'history/createBrowserHistory'
const history = creatHistory();
history.goBack();