How to pass state/props when redirecting to another route in React?

后端 未结 3 1827
夕颜
夕颜 2021-02-05 19:49

I have a signup form and after a user signs up, it will redirect to the email confirmation page(/confirmation) where a user types a confirmation code that I sent via an email. W

相关标签:
3条回答
  • 2021-02-05 20:19

    if you don't want to lose state upon a page refresh you can use local storage:

    handleSubmit() {
      localStorage.setItem('email',
      JSON.stringify(this.state.email));
                   }
    

    and then retrieve from local storage on any other page, perhaps in componentWillMount:

    componentWillMount(){
      let email = '';
      if (localStorage && localStorage.getItem('email')) {
         email = JSON.parse(localStorage.getItem('email'));
        }
       this.setState({email: email})
    }
    
    0 讨论(0)
  • 2021-02-05 20:24

    What i have done to pass data without context object is by using history prop,

    this.props.history.push({
                 pathname:"/shopdetail",
                 state:{
                     key:"value"
                  }
                });
    

    And in the ShopDetail component you can access the object like,

    this.props.location.state.key
    
    0 讨论(0)
  • 2021-02-05 20:26

    I figured it out.

     this.context.router.push({
         pathname: '/confirmation',
         state: {email: this.state.email}  
     })
    

    and access state by:

      this.props.location.state.email
    
    0 讨论(0)
提交回复
热议问题