[英]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.我有名为 Addmember.js 的 reactjs 页面,我可以在其中添加人员。 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'尝试从“react-router-dom”导入withRouter
Then pass the component within withRouter然后在 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.目前 react-router-dom 更新到版本 5,所以你可以使用他们的钩子。
To solve given problem you should import useHistory hook like so import {useHistory} from 'react-router-dom'
要解决给定的问题,您应该像import {useHistory} from 'react-router-dom'
一样导入 useHistory 钩子
Then use it in AddMember like const history = useHistory()
.然后像const history = useHistory()
一样在 AddMember 中使用它。 Then you can use all methods from history where you need it.然后,您可以在需要的地方使用历史记录中的所有方法。 I think it will help for you我想它会对你有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.