首页 > 解决方案 > Redux:将动作创建者导入另一个导致 typeError 'x is not a function'

问题描述

我正面临一个 typeError ,这真的让我很困惑,让我有点发疯:

我有一个汽车动作创建者:

import * as dispatchTypes from '../helper/dispatchTypes';
import { notifyBuyer } from  './buyer';

export const addCar = () => async dispatch => {
  const response = await fetch(someUrl, someBody)

  if (response.ok) {
    const car = await response.json();
    dispatch({type: dispatchTypes.ADD_CAR_RESPONSE, car});
    return notifyBuyer()(dispatch);
  };
}

我在buyer.js 中也有一个notifyBuyer() 的动作创建者:

...
export const notifyBuyer = () => async dispatch => {
...

最后,我也在 React 组件中调用 notifyBuyer():

import * as actions from '../../actions/buyer';

class WhateverComponent extends React.Component {
  constructor(props) {
    super(props);
  }

  doSomething = event => {
    if (!event.disabled) {
      this.props.notifyBuyer(event.toString());
    }
  };

  render() {...}

}

export const StyledComponent = withStyles(styles)(WhateverComponent);
export default connect(
  state => ({}),
  {notifyBuyer: actions.notifyBuyer}
)(StyledComponent);

如果我运行应用程序并使 doSomething 函数运行,我会收到以下错误

TypeError: _this.props.notifyBuyer is not a function

有趣的是:如果我删除“import { notifyBuyer } from './buyer';” 从 car.js 一切都很好。但是一旦在文件中设置了导入,Whatever-Component 的 props 就不再持有 notifyBuyer() 函数,并且抛出 typeError 。

标签: reactjsreduxaction

解决方案


我认为连接函数中使用的导出看起来是错误的。使用下面的示例代码并检查一下。

export default connect(
  state => ({}),
  dispatch => ({notifyBuyer: dispatch(actions.notifyBuyer)})
)(StyledComponent); 

推荐阅读