mapDispatchToProps之后没有找到函数。

问题描述 投票:0回答:1

嗨,所有反应天才们。我是一个新手,我想在这里实现一个很简单的事情。下面是代码,它试图调用一个函数。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)。并尝试添加一个新的组件(FancyAlerter)。所有旧的组件都能得到我的函数,但是,新的组件却无法得到这个函数或其他函数。

所以,我只是不明白我相信的机制。任何帮助都将是非常感激的。


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

reactjs react-redux jhipster
1个回答
4
投票

看来是mapDispatchToProps使用对象的问题。当你使用mapDispatchToProps作为一个对象,你应该提供动作创建者,而不是无效函数。

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.comredux-mapdispatchtoprops-object-form。

测试你的代码。https:/codesandbox.iosicy-lake-h3rxr?file=srcCounterMapDispatchObj.js。


1
投票

谢谢你研究这个问题。我想通了。当然你的回答都帮我排除了可能的原因。

看起来一个组件的导入方式对定义了所有路由的react router文件有很大的影响。

据说下面是我的路由

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

而你导入这个组件的方式是

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

而不是

import  { FancyAlerter }  from './modules/fancyalert/fancyalert';
© www.soinside.com 2019 - 2024. All rights reserved.