HashRouter 与 BrowserRouter

HashRouter

如果是将工程对接到某个现有工程下时,推荐使用此模式。
外部工程的路由 http://localhost/v2/xxx
http://localhost/v2/xxx/#/a 可以访问到具体的页面中
http://localhost/v2/xxx/#/b 可以访问到具体的页面中

  1. import React from 'react';
  2. /**
  3. 通过webpack打包umd包
  4. libraryTarget: 'umd',
  5. library: 'XXXYidaBuild',
  6. */
  7. const XXXYidaBuild = require('./app.bundle')
  8. export default function () {
  9. React.useEffect(() => {
  10. XXXYidaBuild.mount({})
  11. console.log(XXXYidaBuild)
  12. }, [])
  13. return <div id='container'>123</div>
  14. }
  1. /**
  2. 通过webpack打包umd包
  3. libraryTarget: 'umd',
  4. library: 'hibobiYidaBuild',
  5. */
  6. import * as React from 'react';
  7. import * as ReactDOM from 'react-dom';
  8. import * as ReactRouter from 'react-router-dom';
  9. const {
  10. Route,
  11. HashRouter,
  12. Routes,
  13. Link
  14. } = ReactRouter
  15. function Demo (props: {
  16. title: string;
  17. }) {
  18. return <div>
  19. {props.title}
  20. </div>
  21. }
  22. function render (props) {
  23. return ReactDOM.render(
  24. <HashRouter>
  25. <Routes>
  26. <Route path='/a' element={<Demo title='DemoA' />} />
  27. <Route path='/b' element={<Demo title='DemoB' />} />
  28. </Routes>
  29. </HashRouter>
  30. ,
  31. document.getElementById('container'),
  32. );
  33. }
  34. export async function mount (props) {
  35. const __props = props;
  36. render({ ...__props })
  37. }

BrowserRouter

独立工程的可以考虑使用BrowserRouter路由,需要后台辅助

  • http://localhost/ 可以访问到你的页面,此时你在页面中通过Link进行跳转,没有问题,但是如果此时没有后台进行路由的代理时,你通过Link跳转到 http://localhost/a 刷新页面,会404
  • http://localhost/a 直接访问你的页面,此时没有后台进行路由的代理,会404

如果是将工程对接到某个现有工程下时,可以使用 basename
外部工程路由 http://localhost/v2/yida
http://localhost/v2/yida/ 可以访问到具体的页面中
http://localhost/v2/yida/a 可以访问到具体的页面中
http://localhost/v2/yida/b 可以访问到具体的页面中

  1. import * as React from 'react';
  2. import * as ReactDOM from 'react-dom';
  3. import * as ReactRouter from 'react-router-dom';
  4. const {
  5. BrowserRouter,
  6. Route,
  7. Routes,
  8. Link
  9. } = ReactRouter
  10. function Demo (props: {
  11. title: string;
  12. }) {
  13. console.log(props);
  14. return <div>
  15. <div><Link to='/'>Home</Link></div>
  16. <div><Link to='/a'>a</Link></div>
  17. <div><Link to='/b'>b</Link></div >
  18. {props.title}
  19. </div>
  20. }
  21. function render (props) {
  22. const __YidaHibobiConfig = window.YidaHibobiConfig || {}
  23. return ReactDOM.render(
  24. <BrowserRoute basename={props.basename || __YidaHibobiConfig.basename}>
  25. <Routes>
  26. <Route path='/' element={<Demo title='main' />} />
  27. <Route path='/a' element={<Demo title='DemoA' />} />
  28. <Route path='/b' element={<Demo title='DemoB' />} />
  29. </Routes>
  30. </BrowserRouter>
  31. ,
  32. document.getElementById('container'),
  33. );
  34. }
  35. export async function mount (props) {
  36. const __props = props;
  37. render({ ...__props })
  38. }