reactjs - 为什么我得到“TypeError:this.props.login is not a function”,即使我的登录是一个函数
问题描述
使用正确的用户名和密码登录时,会弹出此错误。
TypeError:this.props.login 不是函数
这是 action/auth.js;enter code here
export const login = (username, password) => dispatch => {
const config = {
headers: {
"Content-Type": "application/json"
}
};
const body = JSON.stringify({ username, password });
axios
.post("http://localhost:8000/api/auth/login", body, config)
.then(res => {
dispatch({ type: LOGIN_SUCCESS, payload: res.data });
})
.catch(err => {
console.log(err.message);
});
};
在这里调用登录;
import React, { Component } from "react";
import { Link, Redirect } from "react-router-dom";
import { connect } from "react-redux";
import PropTypes from "prop-types";
import { login } from "../../actions/auth";
class Login extends Component {
state = {
username: "",
password: ""
};
static propTypes = {
login: PropTypes.func.isRequired,
isAuthenticated: PropTypes.bool
};
onSubmit = e => {
e.preventDefault();
this.props.login(this.state.username, this.state.password);
console.log("submited");
};
onChange = e => this.setState({ [e.target.name]: e.target.value });
render() {
if (this.props.isAuthenticated) {
return <Redirect to="/" />;
}
const { username, password } = this.state;
return (
<div className="col-md-6 m-auto">
<form onSubmit={this.onSubmit}>
</form>
</div>
);
}
}
const mapStateToProps = state => ({
isAuthenticated: state.auth.isAuthenticated
});
export default connect(mapStateToProps)(Login);
它没有正确导入,但我的路径是正确的。
我应该使用正确的用户名和密码登录,但无法登录。
解决方案
你不是login()
作为道具传递。您可以通过mapDispatchToProps()
类似于您的方式传递它mapStateToProps()
:
const mapDispatchToProps = dispatch => ({
login: (username, password) => {
dispatch(login(username, password));
},
});
...
export default connect(mapStateToProps, mapDispatchToProps)(Login);
推荐阅读
- javascript - 标记 DOM 节点以供将来查询
- simulation - 如何在 inet 模块中更改 voipstream 的编解码器
- javascript - 防止 Node.js 8+ 因未捕获的异常而退出
- csv - awk 将两个字段输出到一个 CSV 文件中,但 CSV 文件将两个字段放在同一个单元格中
- angular - 过滤 BehaviourSubject.asObservable() 问题
- javascript - 滑块最大值是我的数组中的项目数
- angular - Angular 6:可观察的异步绑定在 HttpErrorResponse 之后无法按预期工作
- ruby-on-rails - Ruby on rails:未初始化的常量 Zip::File::Create
- javascript - jQuery追加到嵌套数组
- angular - 带有数字参数的Angular 6服务发布请求给出错误(404)