React常用知识

React路由配置

2018-11-19  本文已影响47人  朝曦

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

多页面路由配置

//将页面引入和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'),
);

使用react-redux的路由配置

使用react-redux时,需要store进行状态管理,使用Provider组件注入store

./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
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-

上一篇下一篇

猜你喜欢

热点阅读