在使用redux-form时出现Uncaught TypeError: _this.props.onSubmit不是一个函数的错误。

3

我正在使用React.js前端,当我尝试登录或注册时,单击登录注册按钮时会出现以下错误。

Uncaught TypeError: _this.props.onSubmit is not a function

堆栈跟踪指向以下文件, /src/containers/Login/index.js
// @flow
import React, { Component } from 'react';
import { Field, reduxForm } from 'redux-form';
import { Link } from 'react-router-dom';
import { css, StyleSheet } from 'aphrodite';
import Input from '../../components/Input';

const styles = StyleSheet.create({
  card: {
    maxWidth: '500px',
    padding: '3rem 4rem',
    margin: '2rem auto',
  },
});

type Props = {
  onSubmit: () => void,
  handleSubmit: () => void,
  submitting: boolean,
}

class LoginForm extends Component {
  props: Props

  handleSubmit = (data) => this.props.onSubmit(data);
  // handleSubmit: (data) => this.props.onSubmit(data);


  render() {
    const { handleSubmit, submitting } = this.props;

    return (
      <form
        className={`card ${css(styles.card)}`}
        onSubmit={handleSubmit(this.handleSubmit)}
      >
        <h3 style={{ marginBottom: '2rem', textAlign: 'center' }}>Login to Sling</h3>
        <Field name="email" type="text" component={Input} placeholder="Email" />
        <Field name="password" type="password" component={Input} placeholder="Password" />
        <button
          type="submit"
          disabled={submitting}
          className="btn btn-block btn-primary"
        >
          {submitting ? 'Logging in...' : 'Login'}
        </button>
        <hr style={{ margin: '2rem 0' }} />
        <Link to="/signup" className="btn btn-block btn-secondary">
          Create a new account
        </Link>
      </form>
    );
  }
}

const validate = (values) => {
  const errors = {};
  if (!values.email) {
    errors.email = 'Required';
  }
  if (!values.password) {
    errors.password = 'Required';
  }
  return errors;
};

export default reduxForm({
  form: 'login',
  validate,
})(LoginForm);

具体来说,是下面这行代码:

  handleSubmit = (data) => this.props.onSubmit(data);

非常感谢您的帮助。

最后,整个项目可以在这里找到。

2个回答

3

1
在你的 App/index.js 中,你做了以下操作:
 <RedirectAuthenticated path="/login" component={Login} {...authProps} /> 

你可以看到,你没有向登录组件传递一个 onSubmit 函数。
你可以通过对 App/index.js 进行以下更改来修复它。
// add this function
const LoginComponent = () => {
    return (
        <Login onSubmit={() => { console.log("hi") }} />
    )   
}

class App extends Component {
    ...

   render() {
     ....
     <RedirectAuthenticated path="/login" component={LoginComponent} {...authProps} />

在这种情况下,您将会看到“hi”被打印到开发控制台上。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接