javascript - mapDispatchToProps 不起作用 : Uncaught TypeError: _this. props.addCountdown 不是函数

标签 javascript reactjs

我正在尝试构建我的第一个应用程序,但我陷入了困境。我有一个表单组件,它应该通过 onSubmit 处理程序发送对象。

onSubmit = (e) => {
        e.preventDefault();
        this.props.onSubmit({
            title: this.state.title,
            category: this.state.category,
            releaseDate: this.state.releaseDate.valueOf(),
            description: this.state.description
        });
    };

当将 console.log(countdown) 的函数添加到 this.onSubmit() 时,我的 addCountdown 似乎正确接收了所有内容,但是当我尝试将其与我的 addCountdown 操作连接时,它显示 Uncaught TypeError: _this.props.addCountdown is not一个函数。

import React from 'react';
import { connect } from 'react-redux';
import CountdownForm from './CountdownForm';
import { addCountdown } from '../actions/countdowns';

export class AddCountdownItem extends React.Component {
    onSubmit = (countdown) => {
        this.props.addCountdown(countdown);
        this.props.history.push('/');
    }
    render() {
        return (
            <div>
                <h1>Add countdown</h1>
                <CountdownForm onSubmit={this.onSubmit} />
            </div>
        )
    }
}

const mapDispatchToProps = (dispatch) => ({
    addCountdown: (countdown) => dispatch(addCountdown(countdown))
});

export default connect(undefined, mapDispatchToProps)(AddCountdownItem);

这里是 Action :

export const addCountdown = (
    {
      title = '',
      category = '',
      releaseDate = 0,
      description = ''
    } = {}
  ) => ({
    type: 'ADD_COUNTDOWN',
    countdown: {
      title,
      category,
      releaseDate,
      description
    }
  });

console.log(this.props)

添加了沙箱。这是我第一次使用它,所以希望它做得正确。抱歉搞得一团糟,但我才刚刚开始。

https://codesandbox.io/s/github/Lukasz-Gumpert/React-boilerplate

second image

最佳答案

查看您的代码并发现问题...您正在使用未连接的 AddCountdownItem 组件。在您的 AppRouter 文件中,按以下方式导入:

import  AddCountdownItem  from '../components/AddCountdownItem';

这会导入默认导出,在您的情况下,它是连接到 redux 的组件。现在 Prop 已经可用。

关于javascript - mapDispatchToProps 不起作用 : Uncaught TypeError: _this. props.addCountdown 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60834647/

相关文章:

javascript - 填写动态设置为 'visible' 的表单字段

reactjs - 使用 Cypress 或 React 测试库进行集成测试?

javascript - ReactJS引导表单无需刷新页面

reactjs - 如何在 Reactjs 中更改图表的 YAxis 标签的颜色

javascript - 如何点击没有id的链接

javascript - 将带有参数的函数传递给javascript中的另一个函数

javascript - 使用 JQuery 在按下按钮时自动播放全屏 YouTube 视频

javascript - 如何重新加载光滑( slider /旋转木马)jQuery 插件?

javascript - 如何在没有服务器的情况下运行React应用程序

reactjs - 意外的标记 = React JS 类中的第一个函数