简体   繁体   English

如何从库中访问redux商店?

[英]How to access the redux store from a library?

I am creating a library for my react application which will handle every API calls related to the session (authenticate, register, refresh token etc...) and this library will need to access the redux store on its own to dispatch actions. 我正在为我的react应用程序创建一个库,它将处理与会话相关的每个API调用(验证,注册,刷新令牌等......),这个库需要自己访问redux存储来调度操作。 The reason behind this is whenever the access token of the user expires, using a setTimeout I need to call an action creator that will call my API to refresh the token, and update the application redux store with the new session data. 这背后的原因是每当用户的访问令牌到期时,使用setTimeout我需要调用将调用我的API来刷新令牌的动作创建者,并使用新的会话数据更新应用程序redux商店。

So I was thinking to pass the dispatch method to the library whenever I call it for the first time, but I'm not sure that's the best way to do it. 所以每当我第一次调用它时,我都会考虑将调度方法传递给库,但我不确定这是最好的方法。

Or I could also create an initialize() method that will pass the dispatch to the library. 或者我也可以创建一个initialize()方法,将调度传递给库。

import { authenticate } from 'libraries/session';

export function login(email, password) {
    return (dispatch) => {
        dispatch(loginRequest());

        return authenticate(email, password, dispatch) // dispatch is passed here, so I can use it later in the library
        .then(() => (
            dispatch(loginSuccess())
        ))
        .catch((json) => (
            dispatch(loginError());
        ));
    };
};

I haven't tried this code yet, it's more of a brainstorming for now. 我还没有尝试过这个代码,现在更像是一个头脑风暴。

Would you have any suggestion of the best way to handle this? 你对这个问题的最佳方法有什么建议吗?

Thanks! 谢谢!

My impulse would be swap the params: 我的冲动是交换参数:

import { authenticate } from 'libraries/session';


export function configureLogin(store) {
    var {dispatch, subscribe, getState} = store;
    return (email, password) => {
        dispatch(loginRequest());

        return authenticate(email, password, dispatch) // <- I don't why dispatch needs to be included, but I'll take ur word for it
        .then(() => dispatch(loginSuccess())
        .catch(json => dispatch(loginError()));
    };
};

// usage
import { configureLogin } from './service/login';
var store = createStore();
var login = configureLogin(store);
login(email, password);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM