React-router TypeError: _this.props.history is undefined

后端 未结 11 2170
旧时难觅i
旧时难觅i 2020-12-15 16:07

I am using react-router with react js and i following their documentation but facing this error

while compiling it shows the error,

TypeError: _this.         


        
11条回答
  •  甜味超标
    2020-12-15 17:05

    For me the solution was to change

    1) component as child

    
     
    
    

    to

    2) component as the "component" prop

    
    
    

    In both ways it renders, so it was very confusing for me, in examples they provide code as in first example. (I used the version 5.1.2 of the "react-router-dom" package at the moment).

    Update

    You can also use this way (for child components (children of "MyComponent") works only this one)

    import {withRouter} from 'react-router-dom';
    
    const componentClassWithHistory = withRouter(ChildComponent);
    export {componentClassWithHistory as ChildComponent};
    

    or for default export

    export default withRouter(ChildComponent)
    

    or for typescript

    const componentClassWithHistory = (withRouter(ChildComponent as any) as any);
    export {componentClassWithHistory as ChildComponent};
    

    Source: https://reacttraining.com/react-router/core/api/withRouter

    Hope it helps someone.

提交回复
热议问题