我正在尝试使用主页上的登录表单制作简单的应用程序,然后将其重定向到假期页面。尝试将/vacations页面设为私有时,我遇到了问题。这是代码:

import React, { Component } from 'react';
import { Redirect } from "react-router";
import axios from "axios"

class Nav extends Component {
constructor() {
    super();
    this.state = {
        userName: '',
        password: '',
    }
    this.userLogin = this.userLogin.bind(this);
}

  userLogin() {
    let userToChack = {
        userName: this.state.userName,
        password: this.state.password,
    }
    axios.post(`http://localhost:3000/api/login`, userToChack)
        .then(res => {
            if (res.data !== "") {
                // if user name and password OK
                document.getElementById(`helloUser`).innerText = `Hello ${this.state.userName}`;
                document.getElementById(`login`).innerText = `Logout`;
                return <Redirect to='/vacations' />
            } else {
                // if user name or password NOT OK
                console.log("user can't login");
                document.getElementById(`helloUser`).innerText = ``;
                document.getElementById(`login`).innerText =`Login`;
                return <Redirect to='/' />
            }
        })
}
}

最佳答案

您不能在Redirect之外返回render。如果要在执行某些命令性代码后进行重定向,则应使用history.push()

apiCheck = () =>{
    fetchResource().then(res => this.props.history.push('/path'))
}


history对象,当使用Router中的withRouter HOC包装任何组件(已经在react-router-dom下)时,该对象可用

export default withRouter(MyComponent)

关于javascript - 为什么<Redirect to ='/vacations'/>不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57614955/

10-11 17:42