无法从React / Redux中的登录推送

时间:2019-08-01 20:45:51

标签: reactjs authentication redirect redux

尝试在React with Redux中进行Web身份验证,并且所有登录都已设置并可以使用,但是登录后似乎无法重定向到下一页。我已经读过许多答复说要使用this.props.history.push,现在我收到“ TypeError:无法读取未定义的属性'push'”。我认为我对道具和历史有根本的误解。重申一下,它确实进行了身份验证并提供了Web令牌,但我无法自动将用户重定向到/ view-all-cards

我尝试将Navlink放在登录按钮上,这当然不起作用,因为它试图在进行身份验证之前移到受保护的路由。许多人提前感谢您的帮助。

import React, { Component } from 'react';
import axios from 'axios'
import { connect } from 'react-redux'
import { setAuthenticationHeader } from '../utils/authenticate'
import { Route, Redirect, withRouter } from 'react-router'

class Login extends Component {
constructor () {
    super() 

    this.state = {
        username: '',
        password: '',
    }
}


handleTextBoxChange = (e) => {
    this.setState({
        [e.target.name]: e.target.value
    })
}

handleLoginClick = () => {
    axios.post('*****herokuapp.com/****',{
        username: this.state.username,
        password: this.state.password
    }).then(response => {
        let token = response.data.token
        localStorage.setItem('jsonwebtoken',token)
        this.props.onAuthenticated(token)
        setAuthenticationHeader(token)
        this.props.history.push("/view-all-cards")
    }).catch(error => console.log(error))
}

render() {
    return(
        <div> 
            <input name="username" onChange={this.handleTextBoxChange} 
            placeholder='Username'></input>
            <input name="password" type="password" onChange= 
            {this.handleTextBoxChange} placeholder='Password'></input>
            <button onClick={this.handleLoginClick}>Login</button>
        </div> 
    )
    }
}

const mapDispatchToProps = (dispatch) => {
return {
  onAuthenticated: (token) => dispatch({type: 'ON_AUTHENTICATED',
  token:token})
    }
  }

export default connect(null,mapDispatchToProps)(Login)

1 个答案:

答案 0 :(得分:0)

如错误所述,history属性未定义。可能是因为您没有使用withRouter。试试:

export default connect(null,mapDispatchToProps)(withRouter(Login))

为便于说明:history属性仅传播到Route的呈现组件。所有其他子组件都应具有此值,以直接提供或使用withRouter-HOC