ReactJs this.props.router undefined

前端 未结 1 1864
耶瑟儿~
耶瑟儿~ 2021-01-04 08:34

Hello I am learning React js and I have came across a problem. When I try to change back to the main page using react router i get the following error:

U

相关标签:
1条回答
  • 2021-01-04 08:39

    You are missing a constructor method with a call to super(). super() calls the constructor of the parent class and is needed to properly pass the properties of the parents class to this component. You would need this to access any properties passed to the component, including router.

    The top of your layout class should look like this.

    export default class Layout extends React.Component {
      constructor(props) {
        super(props)
      }
    
      navigate() {
        ...
      }
    
      render() {
        ...
      }
    }
    

    Here are the docs on how classes work in ES6!

    Edit 1: React Router

    You also need to use the new withRouter when doing navigation via this.props.router. You do this by passing your component as an argument and exporting that. The withRouter function just wraps your component in another component that passes the router prop down to your component. I should point out that there are other ways of doing programmatic routing (singletons, context, etc.), but when using this.props.router.push you will need to use withRouter.

    import { withRouter } from 'react-router' 
    class Layout extends React.Component {
      constructor(props) {
        super(props)
      }
    
      navigate() {
        ...
      }
    
      render() {
        ...
      }
    }
    
    export default withRouter(Layout)
    

    Using withRouter

    0 讨论(0)
提交回复
热议问题