React Redux - 在辅助函数中访问现有存储

IT技术 javascript reactjs react-redux store
2021-05-11 19:16:00

我试图在react组件之外获取存储实例(存储状态),即在单独的辅助函数中。我有我的减速器,我的动作,我在最上层的组件中创建了一个商店。

// 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());
}

这种方法不起作用,因为 console.log(store.getState()) 返回未定义。但是,如果我将一个 initialConfig 传递给 configStore() 它会构建一个新商店并且一切正常。

感谢帮助。

1个回答

您当前的代码不起作用,因为您正在创建单独的商店index.jshelpers.js而您应该使用相同的 Redux 商店。

您可以将商店初始化代码移动到单独的module中,导出商店并在需要使用它的任何地方导入它。

// 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());
}