如何使用 React.js 从组件重定向回 App?

how to redirect back to App with React.js from a component?

我是 React.js 的新手,我没有找到正确的解决方案。 我有 CreateUser 组件,当客户端成功创建一个组件时,我想将客户端重定向到 App... 我需要它发生在 CreateUser Component

的这个函数中
private handleSubmit(e:any){

        e.preventDefault();
        this.setState({
            username: this.state.username,
            password: this.state.password,
            confirmPassword: this.state.confirmPassword,
            userEmail: this.state.userEmail
        })
        this.passConfrim();
        if (this.isAlertVisible){
            console.log(this.state)
            this.myUserDateService.create(this.state);
---->                               ** Right Here i need to redirect!  **       <----
        }
    }

在if语句的函数末尾

应用程序:

import './App.css';
import { LoginComponent } from './components/LoginComponent';
import CreateUser from './components/CreateUser';
import "bootstrap/dist/css/bootstrap.min.css";
import { Router, Switch, Route, Link, useHistory as history} from "react-router-dom";

function App() {

  return (
    <Router history={history()} >  
                <nav className="navbar navbar-expand navbar-dark bg-dark">
            <a href="/Home" className="navbar-brand">
              To Do List
            </a>
            <div className="navbar-nav mr-auto">
              <li className="nav-item">
                <Link to={"/Login"} className="nav-link">
                Login
                </Link>
              </li>
              <li className="nav-item">
                <Link to={"/CreateUser"} className="nav-link">
                Create User
                </Link>
              </li>
            </div>
          </nav>
            <div id="App-content">
            <Switch >
                <Route exact path={["/", "/Home"]} /> 
                <Route path="/Login" exact component={LoginComponent} />
                <Route path="/CreateUser" exact component={CreateUser} />


            </Switch>
            </div>
    </Router>
  );

}

export default App;

创建用户组件:

import React, { Component } from 'react';
import { UserDataService } from '../services/UserData.service';

interface IState {
    username:string;
    userEmail:string;
    password:string;
    confirmPassword:string;
}

export class CreateUser extends Component <{}, IState> { 

    isAlertVisible: boolean = true;
    myUserDateService = new UserDataService();

    constructor(props: {}, myUserDateService:UserDataService){
        super(props );
        this.state = {
            username:"",
            password:"",
            confirmPassword:"",
            userEmail:"",
        }
    }

    private handleSubmit(e:any){

        e.preventDefault();
        this.setState({
            username: this.state.username,
            password: this.state.password,
            confirmPassword: this.state.confirmPassword,
            userEmail: this.state.userEmail
        })
        this.passConfrim();
        if (this.isAlertVisible){
            console.log(this.state)
            this.myUserDateService.create(this.state);
        }
    }

    passConfrim(){
        if(this.state.password !== this.state.confirmPassword){
            this.isAlertVisible = false;
        }else{
            this.isAlertVisible = true;
        } 
    } 

    render() {

        return (
            <div className="form-group">
                <h1>Create User</h1>
                <form onSubmit={e => this.handleSubmit(e)}>
                    <label >Username</label>
                    <input className="form-control" type="text" placeholder='Enter Username...' onChange={e => this.setState({username : e.target.value})} required/>
                    <br/>
                    <label >Email</label>
                    <input className="form-control" type="text" placeholder='Enter your email...' onChange={e => this.setState({userEmail : e.target.value})} required/>
                    <br/>
                    <label >Passowrd</label>
                    <input className="form-control" type="password" placeholder='Enter Password...' onChange={e => this.setState({password : e.target.value})} required/>
                    <br/>
                    <label >Confirm Passowrd</label>
                    <input className="form-control" type="password" placeholder='Confirm Password...' onChange={e => this.setState({confirmPassword : e.target.value })} required />
                    <div style={{color: "red", textAlign: "left"}} hidden={this.isAlertVisible}>**password not match</div>
                    <br/>
                    <button className="btn btn-primary" type="submit" >Create User</button>
                </form >
            </div>

        )
    }
}

export default CreateUser;

你可以使用 history.push('/yourRoute'),它会带你去任何你想要的路线

由于您是从 React 扩展用户组件,因此它是一个 class 组件,您不能在其中使用 'useHistory' 挂钩。

此外,您正在将历史作为 prop 传递给路由器,能否尝试使用以下代码进行导航并让我知道。

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

基本上你不需要通过 Router 传递历史记录,而是可以使用来自 react-router 的 withRouter 高阶组件。 在 createUser 组件中导入 withRouter - https://reacttraining.com/react-router/core/api/withRouter

import { withRouter } from "react-router";

然后我们只需要导出 CreateUser 组件,例如 -

export default withRouter(CreateUser);

现在您可以访问 CreateUser 组件中与路由相关的所有道具,现在您可以使用 -

this.props.history.push('/your-route');

要检查 withRouter 的其他属性,您可以在 CreateUser 组件中 console.log this.props.history。

提示 - 您不能在 class 组件内使用挂钩,因此您不能在 CreateUser 组件内使用 useHistory 而是使用 withRouter。