簡體   English   中英

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

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

我正在嘗試使用主頁上的登錄表單制作簡單的應用程序,然后重定向到假期頁面。 我在嘗試將/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='/' />
            }
        })
}
}

您不能在render之外返回Redirect 如果你想在一些命令式代碼之后重定向,你應該使用history.push()

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

history對象,它在用react-router-dom withRouter HOC 包裝任何組件(已經在Router下)時withRouter

export default withRouter(MyComponent)

我認為您實際上並不是在渲染組件。 您必須在渲染方法中調用userLogin()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM