Router can have only one child, so wrap all the routes in a _div_ or Switch

只能有一个子元素,<>,div,或 Switch,因为 Router渲染的是 this.props.children
https://reacttraining.com/react-router/web/api/Switch)

Link报错

You should not use outside a

Uncaught Error: Invariant failed: You should not use outside a

_R_eact-route v4 版本后,不允许在Router外部使用Link;需要这样使用
把 Link标签放在 BrowserRouter 里面

  • 如果一个组件要使用路由创建, 那么这个组件必须包裹在BrowserRouter, HashRouter中
  • 将组件包裹在BrowserRouter,或HashRouter中即可
  • React-router4.0版本和React-router2.0版本不兼容的

image.png

  1. import { BrowserRouter as Router, Link } from 'react-router-dom';
  2. <Router>
  3. <Link />
  4. <Link />
  5. </Router>

将BrowserRouter包裹到根节点上,子组件使用withRouter才会生效,不然即使不报错 参数也是获取不到的。

  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. import { BrowserRouter } from 'react-router-dom';
  4. import ReactFastClick from 'react-fastclick';
  5. import './index.css';
  6. import App from './App';
  7. import reportWebVitals from './reportWebVitals';
  8. ReactFastClick(); // 解决 ios点击不生效问题
  9. ReactDOM.render(
  10. <React.StrictMode>
  11. <BrowserRouter> // 包裹根组件
  12. <App />
  13. </BrowserRouter>
  14. </React.StrictMode>,
  15. document.getElementById('root')
  16. );
  17. // If you want to start measuring performance in your app, pass a function
  18. // to log results (for example: reportWebVitals(console.log))
  19. // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
  20. reportWebVitals();