reactjs - 无法从 React/Redux 中的登录推送
问题描述
尝试使用 Redux 在 React 中进行 Web 身份验证,我已经设置并运行了所有登录名,但我似乎无法在登录时重定向到下一页。我读过很多回复说要使用 this.props.history.push,现在我收到“TypeError:无法读取未定义的属性‘push’”。我认为我对道具和历史存在根本性的误解。重申一下,它确实进行了身份验证并提供了一个网络令牌,但我无法让它自动将用户重定向到 /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)
解决方案
正如错误所说,历史属性未定义。可能是因为您没有使用 withRouter。尝试:
export default connect(null,mapDispatchToProps)(withRouter(Login))
解释: history 属性仅传播到 a 的渲染组件Route
。所有其他子组件应具有此值以直接提供或使用withRouter
-HOC
推荐阅读
- android - 为什么我们在android中使用drawable v24?
- javascript - 无法访问 Angular 组件中动态创建的元素
- python - 使用 for 循环将多个 csv 读取到 Python pandas 中的多个数据帧
- javascript - 在两张卡之间导航
- django - django中基于表单输入和字符串操作的查询
- c# - 修改数据时自动从excel读取数据
- android - 无法在本机反应中编辑 TextInput 数据
- ruby - 真正的输入功能
- php - 您在上传多张图片时没有选择要上传的文件
- jade-platform - How do I create an extract for a delta from the command line