【问题标题】:How to share a variable between epics that are in different files?如何在不同文件中的史诗之间共享变量?
【发布时间】:2021-12-17 12:40:01
【问题描述】:

我在我的nextjs 网络应用程序中使用redux-observable。有一个变量必须在epic1 中设置,稍后在epic2 中访问:

let sharedVariable;

const epic1 = (action$, state$) => {
    return action$.pipe(
        // check if the dispatched action is of type action1
        filter(action1.match),
        tap((action) => {
            // create a new instance of A and assign
            // it to sharedVariable
            if (!sharedVariable) {
                sharedVariable = new A();
            }
        }),
        mergeMap((action) => {
            ...
        }),
    )
}

const epic2 = (action$, state$) => {
    return action$.pipe(
        // check if the dispatched action is of type action2
        filter(action2.match),
        map((action) => {
            if (sharedVariable) {
                return action3();
            } else {
                return action4();
            }
        }),
    )
}

我想将史诗放在不同的文件中:epics1.js & epics2.js

当史诗位于不同的文件中时,我应该如何让史诗设置和访问sharedVariable

提前致谢!

【问题讨论】:

    标签: reactjs redux rxjs next.js redux-observable


    【解决方案1】:

    听起来像是 DI 的好案例:docs

    const sharedVariable = {} // can not be primitive type
    const epicMiddleware = createEpicMiddleware({
      dependencies: { sharedVariable }
    });
    
    const epic2 = (action$, state$, { sharedVariable }) => {
     // Rest of code
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-03
      • 1970-01-01
      • 1970-01-01
      • 2010-11-05
      • 1970-01-01
      • 2017-03-27
      • 2016-05-31
      相关资源
      最近更新 更多