Cannot read property ‘push’ of undefined ‘cannot read property ‘push’ of undefined’ cannot read property ‘push’ of undefined ‘cannot read property ‘push’ of undefined
This Header component is introduced in each page, making it a child component
Solutions:
Pass values from parent components to child components
In the parent component, pass a history to the child component
<Header history={this.props.history} />
Copy the code
The subcomponent methods are written the same way
`this.props.history.push('/login')`
Copy the code
However, if the Header component is nested and encapsulated deeper, this is not possible, and the second option is the only option.
Use withRouter
Push (‘/login’) to the page corresponding to the route. However, not all components are directly connected to the route (by route to this component). When these components need routing parameters, use withRouter to pass routing parameters to the component. If the history, location, and match objects of the react-router are passed to the props object, then use this.props.
As you can see, when a non-routed component also wants to access the match, Location, and History objects of the current route, withRouter is a good choice, as it can be interpreted as wrapping a component into a routed component.
Usage:
import { withRouter } from 'react-router-dom' // ... class Header extends React.Component { //... } export default withRouter(Header); // Use withRouter when exportingCopy the code
When you import and use the Header component, you can jump to it using the this.props. History. push method
Correct way to write it:
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'));
123456789101112131415161718192021222324
Copy the code
The content of the BasicLayout component is as follows:
import React from 'react'; import { withRouter } from 'react-router-dom'; Function BasicLayout(props) {console.log({props}) // history,location, etc. WithRouter (<div> XXXXX </div> ); } export default withRouter(BasicLayout);Copy the code