reactjs - 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 也一直是空的......那个对象应该导出所有的功能......有人知道任何解决方案吗?:(
解决方案
您需要在创建函数后导出对象。通常它们会被提升,但在这种情况下,您可能使用的是严格模式,而它们不是。您必须移动导出对象,或者更好地单独导出所有对象,然后在导入它们时编写:
import * as alertActions from 'youfile'
如果你想导出整个对象,你应该像这样导出它:
export default alertActions
然后你需要像这样导入它们:
import alertActions from 'yourfile'
并访问它们:
alrtActions.error()
推荐阅读
- java - 使用函数验证年龄
- sockets - 如何对侦听 unix 套接字文件的服务器进行基准测试?
- wpf - 在 WPF 中,TextBlock 的自动换行是否可以使用 inline Runs 的文本在单词之间而不是在它们的中间生成中断?
- windows-10 - 无法在 1903 中使用 F12Chooser 调试加载项
- arrays - 数组不能强制转换为整数(TypeError)
- node.js - 如何在 Node.js 中使用 express 处理 POST 请求?我编写了以下不起作用的代码
- java - swagger ui web jar在spring项目中是如何工作的?
- amazon-web-services - 无服务器在已经存在时不断尝试创建用户池域
- javascript - firestore onSnapshot 更新值,但不更新 VueJS 中的 DOM
- html - 使用angularjs调用日历函数时渲染一个新的fullcalendar实例