Reactjs mapDispatchToProps的返回值出错
我的代码出现以下错误: 未捕获(承诺中)类型错误:\u this2.props.login不是函数 在Login.js:37(对于一个有效的用户,我会毫无问题地得到消息“Authorized”)。 当我控制台记录道具时,我得到的是**{match:{…},location:{…},history:{…},staticContext:undefined}**Reactjs mapDispatchToProps的返回值出错,reactjs,react-redux,Reactjs,React Redux,我的代码出现以下错误: 未捕获(承诺中)类型错误:\u this2.props.login不是函数 在Login.js:37(对于一个有效的用户,我会毫无问题地得到消息“Authorized”)。 当我控制台记录道具时,我得到的是**{match:{…},location:{…},history:{…},staticContext:undefined}** import React, { Component } from 'react' import fetch from 'isomorphic
import React, { Component } from 'react'
import fetch from 'isomorphic-fetch';
import {connect} from 'react-redux';
import {loginUser} from '../../actions/LoginActions'
export class Login extends Component {
constructor(props) {
super(props)
this.state = {
email:"",
password:""
}
this.handleSubmit=this.handleSubmit.bind(this);
}
handleSubmit(event) {
console.log(this.state.email);
event.preventDefault();
fetch("http://127.0.0.1:3001/user/login",{
method:'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
UserEmail:this.state.email,
Password:this.state.password,
})},{withCredentials:'include'})
.then (res=>res.json())
.then (res=>{
if(res.message==='Authorized'){
console.log("authorized");
console.log(this.props);
let { email, password } = this.state;
**this.props.login(email,password);** //here I get the error
this.setState({
email : "",
password : ""
});
localStorage.setItem('sessionType', res.result.sessionType);
localStorage.setItem("UserId" , res.result.UserId);
}
else{
console.log("error");
}
})
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<formgroup>
<input
type="email"
value={this.state.email}
onChange={(event)=>{this.setState({ email: event.target.value })}}
placeholder="Email"
id="email"
required
/>
</formgroup>
<formgroup>
<input
type="password"
value={this.state.password}
type="password"
onChange={(event)=>{this.setState({ password: event.target.value })}}
placeholder="Password "
id="password"
required
/>
</formgroup>
<input type="submit" value="Submit" />
</form>
</div>
)
}
}
const mapDispatchToProps = (dispatch) => {
return({
login: (email,password) => {dispatch(loginUser(email,password))}
})
}
const mapStateToProps = (state) =>{
return{}
}
export default connect (mapStateToProps,mapDispatchToProps) (Login)
在mapDispatchToProps中,如果返回一个对象,是否尝试删除函数中的括号
const mapDispatchToProps = (dispatch) => {
return {
login: (email,password) => {dispatch(loginUser(email,password))}
}
}
mapDispatchToProps应该只是一个对象
const mapDispatchToProps = {
login: loginUser
}
loginUser是您要导入到mapDispatchToProps的操作,您将其分配为.props.login。您可以发布loginUser操作的代码片段吗?我添加了操作文件,但没有帮助。仍然会出现相同的错误。操作文件中没有loginUser,这可能就是问题所在吗?操作文件中没有loginUser函数哦,好的,您正在尝试在操作中执行一些异步操作?您正在使用操作/存储获取数据。为此,我建议使用thunk作为中间件——同时,我建议您阅读本文
const mapDispatchToProps = {
login: loginUser
}