React Redux - 在辅助函数中访问现有商店 [英] 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());
}
这种方法不起作用,因为console.log(store.getState())返回undefined。但是,如果我将initialConfig传递给configStore(),它会构建一个新商店,一切正常。
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.
感谢您的帮助。
推荐答案
您当前的代码无效,因为您要在 index.js
和<$ c中创建单独的商店$ c> helpers.js 虽然你应该使用相同的Redux商店。
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());
}
这篇关于React Redux - 在辅助函数中访问现有商店的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!