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'),
);

Demo源码地址:https://github.com/wuhuaranran/react-demo-