首页 > 解决方案 > React redux - 动作

问题描述

最近在redux上尽力了,看到了一个非常不错的文件夹结构项目,我尝试了一样的结构,但是同样的方式没有奏效...

例如,我有一个类似这样的路径:./src/_actions,在这个文件夹中我有“user.actions.js”、“alert.actions.js”、“index.js”。

在 alert.actions.js 我有类似的东西:

import { alertConstants } from "../_constants/alert.constants";

export const alertActions = {
  success,
  error,
  clear,
};

function success(message) {
  return { type: alertConstants.SUCCESS, message };
}

function error(message) {
  return { type: alertConstants.ERROR, message };
}

function clear() {
  return { type: alertConstants.CLEAR };
}

而且我很想将它们从一个地方导入到路径为“./../test.js”的文件夹中:

import {alertActions} from "./../_actions";
import {useDispatch} from "react-redux";

export const test = () => {
const dispatch = useDispatch();

return (
<button onClick={() => dispatch(alertActions.success("test"))}> Click </button>
)

}

但我得到类似“alertActions.success”的东西是未定义的。我不知道我做错了什么。在那个项目中,index.js 也一直是空的......那个对象应该导出所有的功能......有人知道任何解决方案吗?:(

标签: reactjsreduxstructureaction

解决方案


您需要在创建函数后导出对象。通常它们会被提升,但在这种情况下,您可能使用的是严格模式,而它们不是。您必须移动导出对象,或者更好地单独导出所有对象,然后在导入它们时编写:

import * as alertActions from 'youfile'

如果你想导出整个对象,你应该像这样导出它:

export default alertActions

然后你需要像这样导入它们:

import alertActions from 'yourfile'

并访问它们:

alrtActions.error()

推荐阅读