this.props.history.push works in some components and not others

后端 未结 5 1736
南旧
南旧 2020-12-25 10:58

I am trying to programmatically change pages using browserHistory.push. In one of my components, but not in a component that I embedded inside of that one.

相关标签:
5条回答
  • 2020-12-25 11:37

    If anyone is still facing similar issues please try to change the onClick to this

    onClick={() => this.props.history.push("/dashboard")}
    

    also if you are in a child component please use the <Redirect to="/dashboard"/> component

    0 讨论(0)
  • 2020-12-25 11:39

    You answered your question in your question.

    As you can see, the components are virtually exactly the same except that the child one is inside the parent one.

    The very fact that the component is nested one further is your issue. React router only injects the routing props to the component it routed to, but not to the components nested with in.

    See the accepted answer to this question. The basic idea is that you now need to find a way to inject the routing props to the child component. You can do that by wrapping the child in a HOC withRouter.

    export default withRouter(connect(mapStateToProps, matchDispatchToProps)(ChildView));
    

    I hope this helps.

    0 讨论(0)
  • 2020-12-25 11:44

    Using withRouter is fine, an alternative option is to pass the history as a prop from parent to child (without using withRouter), e.g:

    Parent

    <SignupForm history={this.props.history}/>
    

    Child

    this.props.history.push('/dashboard');
    
    0 讨论(0)
  • 2020-12-25 11:48

    You Can try this

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

    or pass the history as a prop from parent to child component like

    parent

    <SignupForm history={this.props.history}/>
    

    child

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

    or withRouter

    import { withRouter } from "react-router";
    export default withRouter(connect(mapStateToProps, {
        ...
    })(Header));
    
    0 讨论(0)
  • 2020-12-25 11:55

    This is the problem of Nested Components. I was facing this issue in Header component. I wanted to redirect the page to home page on clicking the logo.

    this.props.history.push won't work in nested components.

    So Solution is to use withRouter .

    To Use withRouter just copy paste Below 2 lines in Header(You can use it in your component) :

    import { withRouter } from "react-router";
    export default withRouter(connect(mapStateToProps, {
        ...
    })(Header));
    
    0 讨论(0)
提交回复
热议问题