Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a react.Component that has a form for a user to signin.

How can I redirect the app to a new page on successfull signin?

import React from "react";
import {
  Link
} from "react-router-dom";
import { withRouter } from "react-router";
import {Header} from  './layout/Header.js';

export class Signin extends React.Component {
 constructor(props){
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
 }

 handleSubmit(e){
  history.push('/dash');
 }
 render() {
   return (// markup)
 }
}

I'm using the Router in App.js to display pages in my app, eg signin and dash.

<Router>
      <Switch>
        <Route path="/signin">
          <Signin />
        </Route>
        <Route path="/dash">
          <Dash />
        </Route>
      </Switch>
</Router>

I get the error "history is undefined"

If i try @MoiioM 's method - I get the error: Unexpected token, expected ","

question from:https://stackoverflow.com/questions/65847229/redirect-from-within-a-react-component

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
198 views
Welcome To Ask or Share your Answers For Others

1 Answer

You need to use the HOC (Higher-Order Component) withRouter on your class, then use the props history.

import React from "react";
import {
  Link
} from "react-router-dom";
import { withRouter } from "react-router";
import {Header} from  './layout/Header.js';

class Signin extends React.Component {
 constructor(props){
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
 }

 handleSubmit(e){
  this.props.history.push('/dash');
 }
 render() {
   return (// markup)
 }
}

//export { withRouter(Signin) as Signin }; // does not work, 

// @brian-thompsons suggestion:
const SigninWrapper = withRouter(Signin);
export { SigninWrapper as Signin };

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...