使用withRouter报错的问题原因及解决办法

我就是我 2023-06-20 06:25 172阅读 0赞

原因是因为你没有把你的Router放在最外面,withRouter不可以放在Router的外面。

比如【下方是错误的】:

在下面的代码中如果你在BasicLayout组件中使用withRouter就会报错:
You should not use outside a

原因是因为你将BasicLayout组件写在了Router外面。

  1. import React from 'react';
  2. import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
  3. import ReactDOM from 'react-dom';
  4. import BasicLayout from './components/common/BasicLayout';
  5. import List from './components/list/List';
  6. import Detail from './components/detail/Detail';
  7. import NotFound from './components/notfound/NotFound';
  8. import './index.css';
  9. const App = () => {
  10. return (
  11. <BasicLayout>
  12. <Router>
  13. <Switch>
  14. <Route exact path="/" component={ List} />
  15. <Route exact path="/currency/:id" component={ Detail} />
  16. <Route component={ NotFound} />
  17. </Switch>
  18. </Router>
  19. </BasicLayout>
  20. );
  21. }
  22. ReactDOM.render(<App />, document.getElementById('root'));

接下来我们来写个正确的写法:

正确的写法:

  1. import React from 'react';
  2. import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
  3. import ReactDOM from 'react-dom';
  4. import Header from './components/common/Header';
  5. import List from './components/list/List';
  6. import Detail from './components/detail/Detail';
  7. import NotFound from './components/notfound/NotFound';
  8. import './index.css';
  9. const App = () => {
  10. return (
  11. <Router>
  12. <BasicLayout>
  13. <Switch>
  14. <Route exact path="/" component={ List} />
  15. <Route exact path="/currency/:id" component={ Detail} />
  16. <Route component={ NotFound} />
  17. </Switch>
  18. </BasicLayout>
  19. </Router>
  20. );
  21. }
  22. ReactDOM.render(<App />, document.getElementById('root'));

BasicLayout组件的内容如下:

  1. import React from 'react';
  2. import { withRouter } from 'react-router-dom';
  3. function BasicLayout(props) {
  4. console.log({ props}) // history,location等等withRouter附加的props就能看到了
  5. return (
  6. <div>
  7. xxxxx
  8. </div>
  9. );
  10. }
  11. export default withRouter(BasicLayout);

OK,问题解决~

发表评论

表情:
评论列表 (有 0 条评论,172人围观)

还没有评论,来说两句吧...

相关阅读