首页 > 解决方案 > 如何修复 reactjs 中的历史推送?

问题描述

我试图将历史推送放在我的登录中,登录后页面将其重定向到另一个页面,在我的登录中它可以工作,但我尝试将它也插入登录页面,但不幸的是它没有重定向任何内容:

登录页面:(使用 axios)

import React, {useState, useEffect} from 'react'
import Axios from 'axios'
import './Register.css'
import styled from 'styled-components'
import Navbar from '../../Components/Navbar/Navbar'
import {useHistory} from 'react-router-dom'

function Register() {
const history = useHistory();

const [emailReg, setEmailReg] = useState("");
const [usernameReg, setUsernameReg] = useState("");
const [passwordReg, setPasswordReg] = useState("");
const [repeatpasswordReg, setRepeatPasswordReg] = useState("");
const [natReg, setNatReg] = useState("");
const [setregStatus, setRegStatus] = useState("");


Axios.defaults.withCredentials = true;

const register = () => {
  Axios.post("http://localhost:3001/register", {
    email: emailReg,
    username: usernameReg,
    password: passwordReg,
    nationality: natReg,
  }).then((response) => {
    history.push('/Login');
    console.log(response);
  })
  };
  return (
    <>
    <Navbar/>
     <Container>
      <div className="login-box1">
        <h1>Sign Up</h1>
            <div className="textbox1">
            <i class="fal fa-envelope"></i>
            <input type="text" placeholder="Email" onChange={(e) => {
        setEmailReg(e.target.value);
      }}/>
            </div>

            <div className="textbox1">
            <i class="fas fa-user-alien"></i>
            <input type="text" placeholder="Username" onChange={(e) => {
           setUsernameReg(e.target.value);
          }}/>
            </div>

            <div className="textbox1">
            <i class="fas fa-globe-americas"></i>
            <input type="text" placeholder="Nationality" onChange={(e) => {
          setNatReg(e.target.value);
          }}/>
            </div>

            <div className="textbox1">
            <i className="fas fa-lock"></i>
            <input type="password" placeholder="Password" onChange={(e) => {
          setPasswordReg(e.target.value);
         }} />
            </div>
            
            <div className="textbox1">
            <i className="fas fa-lock"></i>
            <input type="password" placeholder="Re-peat password" onChange={(e) => {
          setRepeatPasswordReg(e.target.value);
          }} />
            </div>
         <input type="button" class="btn11" value="Sign Up" onClick={register}/>
         </div>
         </Container>
        </>
        )}
         export default Register

如您所见,我定义了 const 历史推送,然后将其调用到 axios const 中,但不幸的是它不起作用,我可以修复它吗?谢谢!!

标签: javascripthtmlreactjsaxios

解决方案


可能的解决方案

  • 用于withRouter涉及组件

  • 创建浏览器历史记录并作为props

    <Router history={history}>
      {/* ...Routes */}
    </Router
    
  • 检查路线是否具有exact正确的属性


推荐阅读