在 React 中从一个页面重定向到另一个页面

Posted

技术标签:

【中文标题】在 React 中从一个页面重定向到另一个页面【英文标题】:Redirecting from one Page to Another in React 【发布时间】:2021-06-24 13:31:32 【问题描述】:

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import  BrowserRouter as Router, Route  from "react-router-dom";

ReactDOM.render(
  <Router>
    <Route path="/" component=App />
  </Router>,
  document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

import  Link, Route, BrowserRouter as Router, Switch  from "react-router-dom";
import "./App.css";
import LoginForm from "./Components/LoginForm";
import Otp from "./Components/Otp";

// import GeoLocation from "./Components/Geolocation"
function App() 
  return (
    <Router>
      " "
      <div className="App">
        <Link to="/">LoginForm</Link>
        <Link to="otp">Otp</Link>
        /* <GeoLocation/> */
        <Switch>
          " "
          <Route path="/" exact component=LoginForm />
          <Route path="otp" component=Otp />
        </Switch>
      </div>
    </Router>
  );


export default App;

import React,  Component  from "react";
import "./LoginForm.css";
import  withRouter  from "react-router-dom";
//import  createBrowserHistory  from "history";
//import axios from 'axios';
//import useHistory from 'react-router-dom';

class LoginForm extends Component 
  constructor(props) 
    super(props);
    this.state = 
      number: "",
      submitting: false,
      error: false,
    ;
  

  onHandleChange = (event) => 
    this.setState( number: event.target.value );
    console.log("Number is: " + this.state.number);
  ;

  onSubmit = (event) => 
    event.preventDefault();
    this.history.push("/otp");
    this.setState( submitting: true );
    console.log(this.state.number);
    fetch("https://d6a898ba0d80.ngrok.io/api/contacts", 
      method: "POST",
      // credentials: 'include',
      headers: 
        Accept: "application/json",
        "Content-Type": "application/json",
        // 'Access-Control-Allow-Origin': 'http://localhost:3002/'
      ,
      body: JSON.stringify( phone: this.state.number ),
    )
      .then((data) => 
        console.log(data);
      )
      .then((data) => 
        if (data) 
          this.setState(
            error: false,
            submitting: false,
            number: "",
          );
          this.history.push("./Otp");
         else 
          this.setState(
            error: true,
            submitting: false,
          );
        
      )
      .catch((err) => console.log(err));
  ;

  render() 
    return (
      <div className="container">
        <div>
          <div className="container1">
            <h1 className="title">Map App</h1>
          </div>
          <form>
            <div className="formInput">
              <p className="paragraph">User Login</p>
              <input
                type="text"
                placeholder="Enter phone number"
                className="form"
                maxLength="10"
                value=this.state.number
                onChange=this.onHandleChange
              />
              <br></br>
              <br></br>
              <button className="button" type="button" onClick=this.onSubmit>
                " "
                Next
              </button>
            </div>
          </form>
        </div>
      </div>
    );
  


export default withRouter(LoginForm);

// import React,  Component  from 'react'
// import "./LoginForm.css";

// class LoginForm extends Component 

//   render() 
//     return (
//       <div class="background-container">
// <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/1231630/moon2.png"  />
// <div class="stars"></div>
// <div class="twinkling"></div>
// <div class="clouds"></div>
// </div>
//     )

//     export default LoginForm;
import React,  Component  from "react";
// import  useHistory  from "react-router-dom";

class Otp extends Component 
  constructor(props) 
    super(props);
    this.state = 
      otp1: "",
      otp2: "",
      otp3: "",
      otp4: "",
      submitting: false,
      error: false,
    ;
    this.onHandleChange = this.onHandleChange.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
  

  onHandleChange = (event) => 
    this.setState( [event.target.name]: event.target.value );
    console.log(
      "Otp is: " + this.state.otp1,
      this.state.otp2,
      this.state.otp3,
      this.state.otp4
    );
  ;

  onSubmit = (event) => 
    event.preventDefault();
    this.setState( submitting: true );
    console.log(this.state.otp);
    fetch("https://d6a898ba0d80.ngrok.io/api/contacts/OTP", 
      method: "POST",
      // credentials: 'include',
      headers: 
        Accept: "application/json",
        "Content-Type": "application/json",
        // 'Access-Control-Allow-Origin': 'http://localhost:3002/'
      ,
      body: JSON.stringify(
        otp1: this.state.otp1,
        otp2: this.state.otp2,
        otp3: this.state.otp3,
        otp4: this.state.otp4,
      ),
    )
      .then((data) => 
        console.log(data);
      )
      .then((data) => 
        if (data) 
          this.setState(
            error: false,
            submitting: false,
            otp1: "",
            otp2: "",
            otp3: "",
            otp4: "",
          );
         else 
          this.setState(
            error: true,
            submitting: false,
          );
        
      )
      .catch((err) => console.log(err));
  ;
  render() 
    return (
      <div className="container">
        <h3 className="validate_otp">Validate OTP</h3>
        <p className="paragraph">
          Please enter the OTP (one time password) to verify your account. A
          Code has been sent to <span className="text-dark">*******179</span>
        </p>
        <form id="otp-screen" method="post">
          <div className="form-row">
            <div className="col form-group">
              <input
                type="text"
                className="otp_filed"
                maxLength="1"
                name="otp1"
                value=this.state.otp1
                onChange=this.onHandleChange
              />
            </div>
            <div className="col form-group">
              <input
                type="text"
                className="otp_filed"
                maxLength="1"
                name="otp2"
                value=this.state.otp2
                onChange=this.onHandleChange
              />
            </div>
            <div className="col form-group">
              <input
                type="text"
                className="otp_filed"
                maxLength="1"
                name="otp3"
                value=this.state.otp3
                onChange=this.onHandleChange
              />
            </div>
            <div className="col form-group">
              <input
                type="text"
                className="otp_filed"
                maxLength="1"
                name="otp4"
                value=this.state.otp4
                onChange=this.onHandleChange
              />
            </div>
          </div>
          <button className="verify_btn" type="submit" onClick=this.onSubmit>
            Verify
          </button>
        </form>
        /* <p class="text-center text-muted mb-0">Not received your code? <a class="btn-link" href="#">Resend code</a></p> */
      </div>
    );
  **strong text**

我想从 login.js 文件重定向到 otp.js 文件,我尝试将 react-router-dom 与 history.push 方法一起使用,但出现错误,例如 - 无法读取未定义的属性 'push' 并且它不会重定向到下一页。

请大家帮我解决这个问题!!!

谢谢

【问题讨论】:

见this answer 谢谢,,,重定向工作正常 【参考方案1】:

您可以尝试在路线中添加斜线,

<Router>
    " "
    <div className="App">
    <Link to="/">LoginForm</Link>
    <Link to="/otp">Otp</Link> // add a slash before your url link
    /* <GeoLocation/> */
    <Switch>
        " "
        <Route path="/" exact component=LoginForm />
        <Route path="/otp" component=Otp /> // add a slash before your url link
    </Switch>
    </div>
</Router>

在构造函数上绑定 onSubmit 函数

constructor(props) 
    super(props);
    this.state = 
        number: "",
        submitting: false,
        error: false,
    ;
    this.onSubmit = this.onSubmit.bind(this);


onSubmit = (event) => 
    this.props.history.push("/otp");

如果 history.push 在 props 中不起作用,您可以使用 createBrowserHistory from history

制作一个history.js文件

import  createBrowserHistory  from 'history';

export default createBrowserHistory();

现在导入该文件,

import history from './path-to-history-file/history';

那么,

history.push('/otp');

【讨论】:

以上是关于在 React 中从一个页面重定向到另一个页面的主要内容,如果未能解决你的问题,请参考以下文章

反应重定向到另一个页面不起作用[重复]

如果登录成功,如何将用户从登录页面重定向到另一个反应页面?

ReactJS:如何以编程方式将用户重定向到另一个页面?

如何在 React js 中从一个页面导航到另一个页面?

PHP 页面跳转到另一个页面的多种方法方法总结

Struts2页面重定向