未捕获的TypeError:this.props.xxx不是React中的函数

时间:2017-04-15 17:32:52

标签: javascript reactjs

我正在使用React.js进行项目,我遇到了一些麻烦。这是我的问题:

我有这个用于创建新配方的组件:

import React, {Component, PropTypes} from 'react';
import { reduxForm } from 'redux-form';
import {Link} from 'react-router';
import { createRecipe } from '../actions/index';

class NewRecipe extends Component {
    static contextTypes = {
        router:PropTypes.object
    };

    onSubmit(props){
            this.props.createRecipe(props).then(() => {
            this.context.router.push('/yourRecipes');
        });
    }

    render(){
        const name = this.props.fields.name;
        const description = this.props.fields.description;
        const handleSubmit = this.props.handleSubmit;
        return(
            <form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
                <h3>New recipe</h3>
                <div>
                    <label>Name</label>
                    <input type="text" className="form-control" {...name} />
                </div>
                <div>
                    <label>Description</label>
                    <input type="text" className="form-control" {...description} />
                </div>
                <button type="submit" className="btn btn-primary btn-primary-spacing">Submit</button>
                <Link to="/yourRecipes" className="btn btn-danger btn-primary-spacing">Cancel</Link>
            </form>
        );
    }
}

export default reduxForm({
    form: 'NewRecipeForm',
    fields: ['name','description']
}, null, { createRecipe })(NewRecipe);

createRecipe 动作创建者在index.js文件中看起来像这样:

export function createRecipe(props){
  const request = axios.post('http://localhost:3001/recipes/new', props);
    return {
        type: CREATE_RECIPE,
        payload: request
    };
}

每当我尝试单击表单的提交按钮时,我会在浏览器控制台中收到此错误:

Uncaught TypeError: this.props.createRecipe is not a function

2 个答案:

答案 0 :(得分:1)

错误是因为在此react类中没有定义此类函数,并且您尝试使用this.props.createRecipe访问它。 一种方法是直接调用createRecipe()作为导入。 还有一种方法是使用来自react-redux的connect并将此类与state和dispatch props连接起来然后你可以使用this.props.createRecipe()

答案 1 :(得分:0)

如果您使用的是redux-form 6.x.x,那么您需要使用connect

NewRecipe = reduxForm({
    form: 'NewRecipeForm',
    fields: ['name','description']
}, null)(NewRecipe);

export default(null, createRecipe)(NewRecipe);