简体   繁体   中英

React Redux - accessing existing store in a helper function

I'm trying to get the store instance (store state) outside a react component, namely in a separate helper function. I have my reducer, my action, I have created a store in the most upper component.

 // configStore.js import { createStore } from 'redux'; import generalReducers from '../reducers/generalReducers'; export default function configStore(initialState) { return createStore(generalReducers, initialState); } // index.js import { Provider } from 'react-redux'; import configStore from './store/configStore'; const initialReduxStoreConfig = { unit: 'm2', language: 'en' } const store = configStore(initialReduxStoreConfig); ReactDOM.render(( <Provider store={store}> <App/> </Provider> ), document.querySelector('#root')); // helpers.js import configStore from '../store/configStore'; const store = configStore(); function getTranslation(key, lang = null) { console.log(store.getState()); } 

This approach is not working as console.log(store.getState()) returns undefined. However, if I pass an initialConfig to configStore() it builds a new store and everything works just fine.

Thanks for help.

Your current code is not working because you're creating separate stores into index.js and helpers.js while you should use same Redux store.

You can move store initialization code into separate module, export store and import it whereever you need to use it.

// configStore.js
import {createStore} from 'redux';
import generalReducers from '../reducers/generalReducers';

export default function configStore(initialState) {
    return createStore(generalReducers, initialState);
}

// store.js
import configStore from './store/configStore';

const initialReduxStoreConfig = {
    unit: 'm2',
    language: 'en'
}

const store = configStore(initialReduxStoreConfig);

export default store;

// index.js
import {Provider} from 'react-redux';
import store from './store';

ReactDOM.render((
    <Provider store={store}>
        <App/>
    </Provider>
), document.querySelector('#root'));

// helpers.js
import store from './store';

function getTranslation(key, lang = null) {
    console.log(store.getState());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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