首页 > 解决方案 > 为什么我得到“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);

它没有正确导入,但我的路径是正确的。

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

标签: reactjs

解决方案


你不是login()作为道具传递。您可以通过mapDispatchToProps()类似于您的方式传递它mapStateToProps()

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

...

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

推荐阅读