【问题标题】:Importing redux action makes other actions undefined导入 redux action 使得其他 action 未定义
【发布时间】:2019-04-09 20:37:31
【问题描述】:

这是我见过的最奇怪的事情之一。这对我来说完全没有意义。简短的版本是我有一个 Redux 动作创建函数。如果我将此函数导入到这个特定的组件文件中,它会使从其文件中导入的每个函数都未定义。

所以,让我们从文件 filterInputModal.actions.js 开始。这包含我使用 redux-starter-kit 创建的 Redux 操作函数:

export const showAddCategoryModal = createAction('showAddCategoryModal');

这就是我一直在使用的功能。现在,这个函数早就被导入到我的 ManageVideoFilters.js 组件中了:

import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { showAddCategoryModal } from 'store/filterInputModal/filterInputModal.actions';

const ManageVideoFilters = (props) => {
    /* Component logic */
};

/* PropTypes and mapStateToProps */

const mapDispatchToProps = (dispatch) => bindActionCreators({
    showAddCategoryModal: () => showAddCategoryModal() // Done this way to avoid passing in a payload, since certain default event payloads cause Redux to print console errors
});

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

到目前为止一切顺利。在我们打破一切之前,让我们看看我的 filterInputModal.reducer.js Redux reducer,也是使用 Redux Starter Kit 创建的:

import { createReducer } from 'redux-starter-kit';
import { showAddCategoryModal } from './filterInputModal.actions';

const initialState = {}; // The initial state for the reducer goes here

const handleShowAddCategoryModal = (state) => {
    /* handle updating the state */
    return state;
};

const actionMap = {
    [showAddCategoryModal]: handleShowAddCategoryModal
};

export default createReducer(initialState, actionMap);

动作映射使用动作创建函数 toString() 作为键,然后我提供自己的函数来处理更新状态。同样,在这一点上,一切都很完美。稍后我们将回到减速器,首先让我们打破常规。

现在我们将转到我的 VideFileEdit.js 组件。如果我们在这个组件中添加以下行,一切都会中断:

import { showAddCategoryModal } from 'store/filterInputModal/filterInputModal.actions';

那么,它是怎么破的呢?

  1. filterInputModal.reducer.js 中 showAddCategoryModal 函数的导入现在未定义。
  2. 由于 reducer 使用函数作为 key 来处理 action,reducer 不再能够正确处理 action 并更新 state。

但它变得更奇怪了。以下是我看到的一些奇怪行为。

  1. 如果我将此操作导入任何其他组件,一切都很好。 reducer 中的导入没有改变。
  2. 在 ManageVideoFilters.js 和 VideoFileEdit.js 中导入函数都可以。

那么,接下来我可以尝试什么?这真的很奇怪,对我来说没有任何意义。我以前从未见过这种情况。

【问题讨论】:

  • 您的文件中有递归导入吗?

标签: reactjs redux


【解决方案1】:

正如评论者所说,问题在于递归导入。我的 filterInputModal.reducer.js 导出了一些常量,这些常量被导入到我的 filterInputModal.actions.js 中。然后将来自 filterInputModal.actions.js 的动作导入到 filterInputModal.reducer.js 中。因此递归导入。

我将常量移到了一个新文件 filterInputModal.constants.js 和 viola 中,问题解决了。

【讨论】:

    猜你喜欢
    • 2018-08-12
    • 2018-03-15
    • 2017-06-30
    • 2021-08-11
    • 2018-11-08
    • 2019-09-14
    • 2018-09-03
    • 2015-03-05
    • 1970-01-01
    相关资源
    最近更新 更多