javascript - React Redux - přístup k existujícímu store v pomocné funkci
Snažím se získat instanci obchodu (stav obchodu) mimo komponentu React, konkrétně v samostatné pomocné funkci. Mám svůj reduktor, svou akci, vytvořil jsem obchod v nejvyšší komponentě.
// 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 přístup nefunguje, protože console.log(store.getState()) vrací undefined. Pokud však předám inicializační konfiguraci do configStore(), vytvoří se nové úložiště a všechno funguje úplně normálně.
Díky za pomoc.
Odpověď č. 1
Váš současný kód nefunguje, protože vytváříte samostatné úložiště v index.js a helpers.js, přitom byste měli používat stejné Redux úložiště.
Můžete přesunout kód inicializace úložiště do samostatného modulu, exportovat úložiště a importovat jej tam, kde ho potřebujete použít.
// 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());
}
