javascript - React Redux - prístup k existujúcemu store vo funkcii pomocníka
Snažím sa získať inštanciu obchodu (stav obchodu) mimo React komponentu, konkrétne v samostatnej pomocnej funkcii. Mám svoj reducer, svoju akciu, vytvoril som obchod v najvyššom komponente.
// 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());
}Tento prístup nefunguje, pretože console.log(store.getState()) vracia undefined. Avšak, ak odovzdám initialConfig do configStore(), vytvorí sa nový store a všetko funguje bez problémov.
Ďakujem za pomoc.
Odpoveď č. 1
Váš súčasný kód nefunguje, pretože vytvárate samostatné úložiská v index.js a helpers.js, zatiaľ čo by ste mali použiť rovnaké Redux úložisko.
Kód inicializácie obchodu môžete presunúť do samostatného modulu, exportovať obchod a importovať ho kdekoľvek, kde ho potrebujete použiť.
// 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());
}
