我正在迭代地重建遗留系统以使用 React/Redux。它在大多数情况下都运行良好!我现在面临的最大问题是旧系统有很多嵌套的 iframe,它们会使用 top.functionName() 与应用程序的其余部分进行通信。由于我无法一次重建所有内容,因此我需要编写某种接口(interface)以通过 top.functionName() 与我的 Redux 存储进行通信。
我知道我可以使用 $r.store.dispatch 将 Action 直接发送到 reducer,但如果可能的话,我真的很想直接使用我的 Action 创建器。有办法实现吗?
最佳答案
用 dispatch
包装的 Action 创建一个对象,并将该对象设置为 window
上的属性:
将您的所有操作作为一个对象导入,或者使用 spread 或
Object#assign
将它们全部组合到一个对象中.//import * as actionCreators1 from actionCreators1 //import * as actionCreators2 from actionCreators2 //import * as actionCreators3 from actionCreators3 const actionCreators = { ...actionCreators1, ...actionCreators2, ...actionCreators3, etc... };
Action 的对象应该是这样的
const actionCreators = { actionA: (payload) => ({ type: 'actionA', payload }), actionB: (payload) => ({ type: 'actionB', payload }), // etc... };
使用
bindActionCreators
包装 Action ,并将它们分配给window
上的属性:const demoStore = createStore(reducer); window.reduxActions = bindActionCreators(actionCreators, demoStore.dispatch);
使用以下方法从 iframe 调用您的操作:
top.reduxActions.actionA(15);
关于javascript - 在使用我的 action creators 时,有没有办法从全局 Vanilla JS 函数与我的 Redux 存储进行通信?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41267955/