安装

npm install react-router-dom —save

Router4.x 是使用react-router-dom作为浏览器端的路由

使用

1、简单使用 BrowserRouter , Route , Link

  1. import { BrowserRouter , Route , Link } from 'react-router-dom';
  2. import React from 'react';
  3. import ReactDom from 'react-dom';
  4. import App1 from './App1';
  5. import { createStore , applyMiddleware , compose } from 'redux';
  6. import thunk from 'redux-thunk';
  7. import { Provider } from 'react-redux';
  8. import { BrowserRouter , Route , Link } from 'react-router-dom';
  9. import {counter} from './Index.redux';
  10. //import { addGun , removeGun , addGunAsync } from './Index.redux';
  11. const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose;
  12. // const store = createStore(counter, /* preloadedState, */ composeEnhancers(
  13. // applyMiddleware(thunk),
  14. // ));
  15. //const reduxDevTools = window.devToolsExtension? window.devToolsExtension() : f=>f;
  16. const store = createStore(
  17. counter,
  18. composeEnhancers(applyMiddleware(thunk))
  19. );
  20. function Erying(){
  21. return <h2>二营</h2>
  22. }
  23. function Qibinglian(){
  24. return <h2>骑兵连</h2>
  25. }
  26. ReactDom.render(
  27. (
  28. <Provider store={store}>
  29. <BrowserRouter>
  30. <div>
  31. <ul>
  32. <li>
  33. <Link to='/'>一营</Link>
  34. </li>
  35. <li>
  36. <Link to='/erying'>二营</Link>
  37. </li>
  38. <li>
  39. <Link to='/qibinglian'>骑兵连</Link>
  40. </li>
  41. </ul>
  42. <Route path='/' exact component={App1}></Route>
  43. <Route path='/erying' component={Erying}></Route>
  44. <Route path='/qibinglian' component={Qibinglian}></Route>
  45. {/* <App1 /> */}
  46. </div>
  47. </BrowserRouter>
  48. </Provider>
  49. ),
  50. document.getElementById('root')
  51. );

2、url参数,Route 组件可以用冒号(:)标识参数

image.png

3、Redirect 组件跳转
重定向路由

  1. //如果没有匹配到路由,就重定向 404
  2. <Redirect to='/NotFound'></Redirect>

4、Switch只渲染一个组件

  1. <Switch>
  2. <Route path='/' exact component={App1}></Route>
  3. <Route path='/erying' component={Erying}></Route>
  4. <Route path='/qibinglian' component={Qibinglian}></Route>
  5. <Route path='/:location' component={Test}></Route>
  6. {/* <App1 /> */}
  7. </Switch>