原因是因为你没有把你的Router放在最外面,withRouter不可以放在Router的外面。
比如【下方是错误的】:
在下面的代码中如果你在BasicLayout组件中使用withRouter就会报错:
You should not use <withRouter(BasicLayout) /> outside a <Router>
原因是因为你将BasicLayout组件写在了Router外面。
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import ReactDOM from 'react-dom';
import BasicLayout from './components/common/BasicLayout';
import List from './components/list/List';
import Detail from './components/detail/Detail';
import NotFound from './components/notfound/NotFound';
import './index.css';
const App = () => {
return (
<BasicLayout>
<Router>
<Switch>
<Route exact path="/" component={List} />
<Route exact path="/currency/:id" component={Detail} />
<Route component={NotFound} />
</Switch>
</Router>
</BasicLayout>
);
}
ReactDOM.render(<App />, document.getElementById('root'));
接下来我们来写个正确的写法:
正确的写法:
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import ReactDOM from 'react-dom';
import Header from './components/common/Header';
import List from './components/list/List';
import Detail from './components/detail/Detail';
import NotFound from './components/notfound/NotFound';
import './index.css';
const App = () => {
return (
<Router>
<BasicLayout>
<Switch>
<Route exact path="/" component={List} />
<Route exact path="/currency/:id" component={Detail} />
<Route component={NotFound} />
</Switch>
</BasicLayout>
</Router>
);
}
ReactDOM.render(<App />, document.getElementById('root'));
BasicLayout组件的内容如下:
import React from 'react';
import { withRouter } from 'react-router-dom';
function BasicLayout(props) {
console.log({props}) // history,location等等withRouter附加的props就能看到了
return (
<div>
xxxxx
</div>
);
}
export default withRouter(BasicLayout);
OK,问题解决~