在 mapDispatchToProps 之后找不到函数

function not found after mapDispatchToProps

大家好反应天才。我是新手,我想在这里实现一件非常简单的事情。 下面是代码,它试图在单击按钮时调用函数 sentTheAlert()。但是,我的控制台出现错误。

import React from 'react';
import { connect } from 'react-redux';
import { Button } from 'reactstrap';
import { RouteComponentProps } from 'react-router-dom';

export interface IFancyAlerterProps extends StateProps, DispatchProps, RouteComponentProps<{}> {}

export class FancyAlerter extends React.Component<IFancyAlerterProps> {
  handleSubmit= () => {
    this.props.sendTheAlert('hello');
  };

  render() {
    return (
      <div>
        <h1>Today Fancy Alert is {this.props.fancyInfo}</h1>
        <Button color="primary" onClick={this.handleSubmit}>
          See my Alert
        </Button>
      </div>
    );
  }
}

const SEND_MESSAGE = 'SEND_MESSAGE';

interface SendAlertType {
  type: typeof SEND_MESSAGE;
  payload: string;
}

function sendTheAlert(newMessage: string): SendAlertType {
  return {
    type: SEND_MESSAGE,
    payload: newMessage,
  };
}
const mapDispatchToProps = { sendTheAlert };

function mapStateToProps(state) {
  return { fancyInfo: 'Fancy this:' + state.currentFunnyString };
}

type StateProps = ReturnType<typeof mapStateToProps>;
type DispatchProps = typeof mapDispatchToProps;

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

注意:如果此信息有帮助,我会使用 React UI 创建一个 jhispter 应用程序。并尝试添加一个新组件(FancyAlerter)。所有旧组件都能获得我的功能,但是新组件无法获得此功能或任何其他功能。

所以,我就是不明白我所相信的机制。非常感谢任何帮助。


更新:在上面的代码中,道具包含来自 RouteComponentProps 的方法,但不包含来自其他两种类型的方法。

使用 mapDispatchToProps 对象似乎有问题。当您将 mapDispatchToProps 用作对象时,您应该提供 action creator,而不是 void function :

const SEND_MESSAGE = 'SEND_MESSAGE'

interface SendAlertType {
  type: typeof SEND_MESSAGE
  payload: String
}

function sendTheAlert(newMessage: String): SendAlertType {
  return {
    type: SEND_MESSAGE,
    payload: newMessage
  }
}

const mapDispatchToProps = { sendTheAlert };

稍后您可以在中间件(saga、thunk 等)上发出警报。

检查用法:https://daveceddia.com/redux-mapdispatchtoprops-object-form/

测试您的代码:https://codesandbox.io/s/icy-lake-h3rxr?file=/src/CounterMapDispatchObj.js

感谢您调查问题。我想到了。当然,您所有的回答都帮助我排除了可能的原因。

似乎组件的导入方式与定义所有路由的 react 路由器文件有很大不同。

下面应该是我的路线

<ErrorBoundaryRoute path="/fancy" component={FancyAlerter} />

导入这个组件的方式是

import  FancyAlerter  from './modules/fancyalert/fancyalert';

而不是

import  { FancyAlerter }  from './modules/fancyalert/fancyalert';