简体   繁体   English

为什么<Redirect to='/vacations' />不起作用

[英]why <Redirect to='/vacations' /> Does not work

I am trying to make simple app with login form on the home page, which redirects then to vacations page.我正在尝试使用主页上的登录表单制作简单的应用程序,然后重定向到假期页面。 I faced a problem when trying to make /vacations page private.我在尝试将/vacations页面设为私有时遇到了问题。 Here is the code:这是代码:

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='/' />
            }
        })
}
}

You can't return Redirect outside render .您不能在render之外返回Redirect If you want to redirect after some imperative code you should use history.push()如果你想在一些命令式代码之后重定向,你应该使用history.push()

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

history object it's available when wrapping any component (that already is under Router ) with withRouter HOC from react-router-dom history对象,它在用react-router-dom withRouter HOC 包装任何组件(已经在Router下)时withRouter

export default withRouter(MyComponent)

I don't think that you're actually rendering the component.我认为您实际上并不是在渲染组件。 You have to call userLogin() in your render method.您必须在渲染方法中调用userLogin()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM