Redux state value globally

别来无恙 提交于 2019-12-22 10:34:24

问题


I am having a helper class which provies info about the logged in user. I would like to have it as a static method and use it in several places ( which are not react components)

How to get access the redux store value in a class model ?


回答1:


One way could be set a global variable

window.store = createStore(...)

and use it, accessing window.store




回答2:


If you can manage this in your application it would be cleaner (and more testable) to pass it around with dependency injection (DI) as opposed to using a global variable, static or singleton. In a simple form you could just pass it in the constructor like this:

var store = createStore(...);
var app = new AppClass(store);



回答3:


If you're not using a bundler like Webpack, Lukas Katayama's answer should work window.store = createStore(...) but if you are using one, you can also expose your redux store by exporting it and importing where you need it.

//store.js
export const store = createStore(...);

//other file
import { store } from './store.js';

const someFuncOrClass = (...) => {
    const user = store.getState().userInfo;
}



回答4:


Looks like a straight forward implementation. You can create a getter for store in the same file where you creatStore(...).

store.js

import { createStore } from 'redux';

let store = {};

export default function store(...) {
    /*
     * things to do before creating store
     */

    store = createStore(...);
    return store;
}

export function getStore() {
    return store;
}

helper.js

import { getStore } from './store';

export function getUserInfo() {
    const store = getStore();
    const globalState = store.getState();

    return globalState.userInfo;
}


来源:https://stackoverflow.com/questions/40779786/redux-state-value-globally

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!