【问题标题】:React Router navigation using history push使用历史推送反应路由器导航
【发布时间】:2020-09-06 18:59:35
【问题描述】:

我是 ReactJS 的新手。当我尝试从一个页面导航到另一个页面时,我坚持使用 React 路由 history.push('/newpage') 对我不起作用。登录服务调用成功我想导航到另一个页面。

我使用的是以下版本

“反应”:“^16.13.1”, “反应域”:“^16.13.1”, "react-router-dom": "^5.2.0",

import React, { Component } from 'react';
import { useHistory } from 'react-router-dom';
import '../Login/Login.css';
import {Auth} from '../../services/Api';
// import { Redirect } from 'react-router-dom'
class Login extends Component {

    constructor(props) {
        super(props)
        this.state = {
            userName: '',
            password: ''
        }
        this.changeEventReact = this.changeEventReact.bind(this);
        this.login = this.login.bind(this);
    }
    changeEventReact = (e) =>{
        this.setState({[e.target.name]: e.target.value});
        // console.log(this.state);
    }
    login = e=>{
        // console.log(this.state);
        Auth('login', this.state)
        .then((result)=>{
            let responseJSON = result;
            if(responseJSON.data.id != ''){
                console.log("Login success");
                const history = useHistory();
                let path = `/facilityRegister`; 
                history.push(path);
            }else{
                console.log('Login failed');
            }
        });
    }

我们可以使用以下三种方法来做到这一点

1. history.push('/facilityRegister')
2. <Redirect to='/facilityRegister'/>
3. window.location.href("/facilityRegister')

window.location.href 正在按预期工作。但是 history.push 并不起作用。

让我知道我错过了什么。

【问题讨论】:

  • 试试 this.props.history.push('/path')
  • @VyasArpit:尝试使用 this.props.history.push('/path');不管用。在类组件中,我们不能使用历史记录

标签: javascript reactjs react-redux react-router


【解决方案1】:

根据反应faq

你不能在类组件中使用 Hooks

这就是const history = useHistory(); 在这里不起作用的原因。但无论如何你can't use hooks inside async functions。请改用withRouter HOC 或尝试将您的组件重写为功能。

【讨论】:

    【解决方案2】:

    前面说钩子不能用在类组件中,只能用在这样的函数组件中

    const app = (props) => {
         const history = useHistory();
         history.push("/path");
    }
    

    你可以试试这个props.history.push("/path")

    希望对你有帮助:)

    【讨论】:

    • 我试图将类组件转换为功能组件并抛出错误。不能在回调中调用 React Hook “useHistory”。 React Hooks 必须在 React 函数组件或自定义 React Hook 函数 react-hooks/rules-of-hooks 中调用。下面是类组件方法调用。 const login = e=>{ console.log("登录成功");常量历史 = useHistory();让路径 = /facilityRegister; history.push(路径); }
    猜你喜欢
    • 2021-04-03
    • 2020-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-14
    • 2021-08-25
    • 2016-05-28
    • 2018-01-02
    相关资源
    最近更新 更多