未捕获的TypeError:dispatch(...)。则不是函数

时间:2018-07-13 14:34:04

标签: reactjs react-redux react-thunk

容器组件

import { connect } from 'react-redux';
import { signUpUser } from '../actions/userActions';

import Register from '../components/register';

function mapStateToProps(state) {
    return { 
      user: state.user
    };
}

const mapDispatchToProps = (dispatch, ownProps) => {
    return {

    }
}

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

注册表格

import React, { Component, PropTypes } from 'react';
import { Link } from 'react-router-dom';
import { reduxForm, Field, SubmissionError } from 'redux-form';
import { signUpUser } from '../actions/userActions';

//Client side validation
function validate(values) {
  var errors = {};
  var hasErrors = false;


  return hasErrors && errors;
}

//For any field errors upon submission (i.e. not instant check)
const validateAndSignUpUser = (values, dispatch) => {
    //console.log(values);
    return dispatch(signUpUser(values))
      .then((response) => {
      console.log(response);
    });
};


class SignUpForm extends Component {

  render() {
    const { handleSubmit } = this.props;
    return (
      <div className="col-md-6 col-md-offset-3">
        <h2>Register</h2>
        <form onSubmit={ handleSubmit(validateAndSignUpUser) }>
          <div className ='form-group'>
              <label htmlFor="firstname">Name</label>
              <Field name="firstname" type="text" component= "input"/>
          </div>
          <div className ='form-group'>
              <label htmlFor="username">Username</label>
              <Field name="username" type="text" component= "input"/>
          </div>
          <div className ='form-group'>
              <label htmlFor="password">Password</label>
              <Field name="password" type="text" component= "input"/>
          </div>
          <div className="form-group">
              <button className="btn btn-primary">Register</button>
              <Link to="/" className="btn btn-error"> Cancel </Link>
          </div>
      </form>
     </div>
    )
  }
}

export default reduxForm({
  form: 'SignUpForm', // a unique identifier for this form
  validate
})(SignUpForm)

动作

import axios from 'axios';

export function signUpUser(user) {
  console.log(user);

  const url = `https://jsonplaceholder.typicode.com/posts`
  const request = axios.get(url); 

  return {
    type: 'Register_User',
    payload: request
  };
}

提交此表格时,出现以下错误。 此应用程序在组合减速器中使用thunk设置形式的减速器。 我要去哪里错了?我是redux-form和thunk的新手

Uncaught TypeError: dispatch(...).then is not a function

1 个答案:

答案 0 :(得分:4)

dispatch的返回值是内部函数的返回值,在您的情况下是对象,而不是promise。 (https://github.com/reduxjs/redux-thunk#composition) 您必须直接在操作中返回axios.get(...)(基本上会返回一个Promise),以便像您在示例中一样,对dispatch的返回值调用then()

我建议做的是不要将注册请求放在单独的操作中,因为在redux表单的提交功能中更容易处理请求。否则,可能很难处理带有验证消息的服务器响应。我还认为您无需在其他任何地方重复使用操作,对吗?如果您需要在注册后更改状态,则可以简单地创建另一个操作,例如“ signedUpUser”,并将一些数据传递给它。