首页 > 解决方案 > 使用历史推送反应路由器导航

问题描述

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

我正在使用以下版本

“react”:“^16.13.1”,“react-dom”:“^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 并不起作用。

让我知道我错过了什么。

标签: javascriptreactjsreact-reduxreact-router

解决方案


根据反应常见问题解答

你不能在类组件中使用 Hooks

这就是为什么const history = useHistory();不在这里工作的原因。但无论如何,你不能在异步函数中使用钩子。改用withRouter HOC 或尝试将您的组件重写为功能。


推荐阅读