为什么我得到“ TypeError:this.props.login不是函数”的原因,即使我的登录名是函数

时间:2019-10-19 07:05:35

标签: reactjs

使用正确的用户名和密码登录时,会弹出此错误。

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);

导入不正确,但是我的路径正确。

我应该使用正确的用户名和密码登录,但无法登录。

1 个答案:

答案 0 :(得分:0)

您没有通过login()作为道具。您可以像这样mapDispatchToProps()通过mapStateToProps()传递它:

const mapDispatchToProps = dispatch => ({
  login: (username, password) => {
    dispatch(login(username, password));
  },
});

...

export default connect(mapStateToProps, mapDispatchToProps)(Login);