React路由簡單配置
//入口文件index.js import React from 'react'; import ReactDom from 'react-dom'; import { Router, Route, BrowserRouter,Switch } from 'react-router-dom'; import createBrowserHistory from "history/createBrowserHistory"; import routeTest from './pages/routeTest'; import Home from './Home'; const history = createBrowserHistory(); ReactDom.render( <Router history={history}> <Switch> <Route path='/' exact component={Home} /> <Route path='/hooksDemo' exact component={routeTest} /> </Switch> </Router >, document.getElementById('app') );
- Router的
history是必需的props - Router中只能有一個子元素
- Switch:只渲染第一個與當前地址匹配的
<Route> - Route的
props path為路徑,component為路徑對應的頁面,exact精確匹配
這是一個簡單的路由配置,可以實現頁面的簡單跳轉,但是如果頁面比較多,可以把頁面組件引入和Route組件提取出來,以保證入口頁面良好的可閱讀性。
多頁面路由配置
//將頁面引入和Route組件提取到./App.js import React from 'react'; import { Router, Route, Switch } from 'react-router-dom'; import PropTypes from 'prop-types'; import routeTest from './pages/routeTest'; import Home from './Home'; const App = ({ history }) => ( <Router history={history}> <Switch> <Route exact path='/' exact component={Home} /> <Route exact path='/hooksDemo' exact component={routeTest} /> </Switch> </Router> ); App.propTypes = { history: PropTypes.shape({}).isRequired }; export default App;
// ./index.js import React from 'react'; import ReactDom from 'react-dom'; import { Router, Route, BrowserRouter,Switch } from 'react-router-dom'; import createBrowserHistory from "history/createBrowserHistory"; import App from './App'; const history = createBrowserHistory(); ReactDom.render( <App history={history} />, document.getElementById('app'), );
- 這樣一來,當項目比較大,頁面很多的時候,頁面引入和
Route定義的部分都被拆分到./App.js中,./index.js只需引入./App.js即可。
使用react-redux的路由配置
使用react-redux時,需要store進行狀態管理,使用Provider組件注入store。
./store,js創建storeTree。
./store.js import { createStore, combineReducers, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import routeTestReducer from 'pages/routeTest/indexRedux'; const storeTree = combineReducers({ routeTestReducer }); const store = createStore(storeTree, applyMiddleware(thunk)); export default store;
./index.js使用Provider組件傳遞store。
./index.js import React from 'react'; import ReactDom from 'react-dom'; import { Router, Route, BrowserRouter,Switch } from 'react-router-dom'; import createBrowserHistory from "history/createBrowserHistory"; import { Provider } from 'react-redux'; import store from './store'; import App from './App'; const history = createBrowserHistory(); ReactDom.render( <Provider store={store}> <App history={history} /> </Provider>, document.getElementById('app'), );
