javascript - 在使用我的 action creators 时,有没有办法从全局 Vanilla JS 函数与我的 Redux 存储进行通信?

标签 javascript redux

我正在迭代地重建遗留系统以使用 React/Redux。它在大多数情况下都运行良好!我现在面临的最大问题是旧系统有很多嵌套的 iframe,它们会使用 top.functionName() 与应用程序的其余部分进行通信。由于我无法一次重建所有内容,因此我需要编写某种接口(interface)以通过 top.functionName() 与我的 Redux 存储进行通信。

我知道我可以使用 $r.store.dispatch 将 Action 直接发送到 reducer,但如果可能的话,我真的很想直接使用我的 Action 创建器。有办法实现吗?

最佳答案

dispatch 包装的 Action 创建一个对象,并将该对象设置为 window 上的属性:

  1. 将您的所有操作作为一个对象导入,或者使用 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...
    };
    
  2. 使用 bindActionCreators 包装 Action ,并将它们分配给 window 上的属性:

    const demoStore = createStore(reducer);
    
    window.reduxActions = bindActionCreators(actionCreators, demoStore.dispatch);
    
  3. 使用以下方法从 iframe 调用您的操作:

    top.reduxActions.actionA(15);
    

关于javascript - 在使用我的 action creators 时,有没有办法从全局 Vanilla JS 函数与我的 Redux 存储进行通信?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41267955/

相关文章:

javascript - 如何从 eBay 通知中获取数据

javascript - 如何防止传单弹出窗口中的表单出现 "submit"事件

javascript - 当另一个组件发生某些事情时 react : How to update one component,

javascript - <LINK> ReactJS 更改 url 但不渲染任何内容

javascript - 如何在 Titanium Appcelerator 中创建带有复选框设置的 ListView

JavaScript/Firefox : "Failed to register/update ServiceWorker", 当没有使用名为 ServiceWorker 的内容时

angular - @ngrx 具有多个有效负载的操作

reactjs - FileReader - 如何在商店更新后更新本地状态?

reactjs - 如何处理 oidc 静默更新错误

c# - 如何在回发时将控件 clientID 添加到 Request.Form 集合