【问题标题】:React router dom v5 history.push does not render new page反应路由器 dom v5 history.push 不呈现新页面
【发布时间】:2022-01-06 04:08:06
【问题描述】:

我需要在登录后将用户重定向到他们的个人资料页面,然后尝试在 Axios 中使用 history.push()。这是我的登录表单代码。我使用onClick按钮获取用户的电子邮件和密码,然后将它们重定向到新页面ClientProfile:

SignIn.js

import React from 'react';
import {Form, Button} from 'react-bootstrap';
import { useState } from 'react';
import Axios from 'axios';
import { useHistory } from 'react-router-dom';

function SignIn() {

    const history = useHistory();

  const [userEmail, setEmail] = useState("");
  const [userPassword, setPassword] = useState("");

//after onClick
  const signIn = () => {

//get user input
    Axios.post("http://localhost:8800/signIn", {
      userEmail: userEmail,
      userPassword: userPassword,
    }).then((res) => {
        console.log(res);
        history.push('/clientprofile');
  })};

    return (
        <Form>
            <Form.Group className="mb-3" controlId="formBasicEmail">
                <Form.Label>Email address</Form.Label>
                <Form.Control type="email" placeholder="Enter your email here"  
                        onChange = {(event) => {
                          setEmail(event.target.value);
                        }}
                      />
            </Form.Group>

            <Form.Group className="mb-3" controlId="formBasicPassword">
                <Form.Label>Password</Form.Label>
                <Form.Control type="password" placeholder="Enter your password here" 
                    onChange = {(event) => {
                      setPassword(event.target.value);
                    }}
                    />
            </Form.Group>
            
            <Button variant="primary" type="submit" onClick={ signIn }>
                Submit
            </Button>
        </Form>
    )
}

export default SignIn;

我在 app.js 中定义了路由:

import './App.css';
import { Navbar, Nav, Container, Image } from 'react-bootstrap';
import About from './Components/About';
import Services from './Components/Services';
import Help from './Components/Help';
import SignIn from './Components/SignIn';
import ClientProfile from './Components/ClientProfile';
import { Switch, Route, NavLink } from 'react-router-dom';

function App() {


  return (
    <div className="App">
      <Navbar className="mainNav">
                <Container>
                        <Nav className="right-side me-auto">
                            <Nav.Link as = {NavLink} to = '/' className="text-white p-3">About Us</Nav.Link>
                            <Nav.Link as = {NavLink} to = '/ourservices' className="text-white p-3">Our Services</Nav.Link>
                            <Nav.Link as = {NavLink} to = '/help' className="text-white p-3">Help</Nav.Link>
                            <Nav.Link as = {NavLink} to = '/signin' className="rounded-pill m-1 px-3 py-2 text-white signInBtn">Sign In</Nav.Link>
                        </Nav>
                </Container>
      </Navbar>
      <br/>
      
      <Switch>
        <Route exact path = "/"><About /></Route>
        <Route path = "/ourservices" ><Services /></Route>
        <Route path = "/help" ><Help /></Route>
        <Route path = "/signin"><SignIn /></Route>

//the route is being defined here
        <Route path = "/clientprofile"><ClientProfile/></Route>
      </Switch>
    </div>
  );
}

export default App;

但是,它不会呈现新页面,而是停留在同一页面上,即登录页面。谁能帮帮我?

【问题讨论】:

  • isRedirect 从 false 变为 true 可能会有延迟。无论哪种方式,如果您仍然想要重定向,为什么要更改该状态值?
  • @AlexanderStaroselsky 我试过了,结果还是一样。无论如何,更新问题

标签: javascript reactjs axios react-router-dom


【解决方案1】:

问题

您正在提交表单,但并未阻止默认表单操作的发生。这会在处理 POST 请求响应和重定向 UI 之前重新加载页面。

解决方案

onClick={signIn} 移动到Form 组件并将其切换到onSubmit 处理程序,并在signin 处理程序中使用onSubmit 事件对象并阻止默认表单操作。

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

  const [userEmail, setEmail] = useState("");
  const [userPassword, setPassword] = useState("");

  //after onClick
  const signIn = (e) => { // <-- onSubmit event object
    e.preventDefault();   // <-- preventDefault
    // get user input
    Axios.post("http://localhost:8800/signIn", {
      userEmail: userEmail,
      userPassword: userPassword
    }).then((res) => {
      console.log(res);
      history.push("/clientprofile");
    });
  };

  return (
    <Form onSubmit={signIn}> // <-- onSubmit event handler
      ...

      <Button variant="primary" type="submit"> // <-- remove onClick handler
        Submit
      </Button>
    </Form>
  );
}

【讨论】:

    【解决方案2】:
    const signIn = () => {
    
    //get user input
        Axios.post("http://localhost:8800/signIn", {
          userEmail: userEmail,
          userPassword: userPassword,
        }).then((res) => {
            console.log(res);
            setIsRedirect(true)
    
    //redirect user
            if(isRedirect){
              history.push('/clientprofile');
            }
      })};
    

    在这里,在 .then 处理程序中,您正在更新状态,并在其下方检查更新的状态。

    但是 React 会异步更新状态。所以更新后的状态不会在这里可用。

    相反,您可以使用 useEffect 挂钩并监听 isRedirect 状态的更新,并在此基础上执行您的操作。

    useEffect(()=>{
    
    if(isRedirect){
        history.push('/clientprofile');
    }
    
    },[isRedirect,history])
    

    【讨论】:

    • 它给了我这个错误:React Hook useEffect has a missing dependency: 'history'
    • history添加到useEffect的依赖数组中
    • 啊,这解决了缺少依赖的问题,但它仍然不会让我重定向到新页面。当我检查控制台时,没有显示错误,但consoloe.log(res) 也没有返回任何内容。会不会是 Axios 内部的问题?
    • 可能是这样,你要检查你的axios是否正确获取
    【解决方案3】:
    • 对于react router dom小于6.^的版本

    你可以像你的代码显示的那样使用useHistory()钩子

    • 对于react router dom大于6.^的最新版本

    你可以像这样使用useNavigate()钩子。

    import { useNavigate } from 'react-router-dom';
    
    const signIn = () => {
      ....
    
      let navigate = useNavigate();
    
             .....
             ......
    
          navigate('/clientprofile');
        
        .....
    
      }
    

    所以请检查您在 package.json 文件中的 react-router-dom 版本并进行相应操作。

    【讨论】:

    • OP 正在使用 Switch 组件和 useHistory 钩子,没有任何构建错误,假设在这里使用 RRDv5 可能是安全的。
    猜你喜欢
    • 1970-01-01
    • 2020-12-25
    • 2021-11-14
    • 2020-12-02
    • 2022-08-22
    • 2018-02-23
    • 2021-04-23
    • 2020-12-08
    • 2018-04-01
    相关资源
    最近更新 更多