简体   繁体   中英

The 'this.props.history.push()' is working for normal page but not working for nested components?

I have reactjs page called Addmember.js,where I can add people. And I have a next button which will take me to dashboard via the following code

 this.props.history.push('/dashboard')

But the real problem arises, when I use the Add member component inside a new page, when i click next its showing the below error

Cannot read property 'push' of undefined

Help will be Appreciated!

Try importing withRouter from 'react-router-dom'

Then pass the component within withRouter

For eg.

export default withRouter(Addmember);

The problem is because your component can not find history props when you nest it. Currently react-router-dom updated to the version 5, so you can use their hooks.

To solve given problem you should import useHistory hook like so import {useHistory} from 'react-router-dom'

Then use it in AddMember like const history = useHistory() . Then you can use all methods from history where you need it. I think it will help for you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM