我正在尝试将存储实例(存储状态)放到一个反应性组件之外,即在一个单独的助手函数中。我有我的减速机,我的动作,我已经创建了一个商店在最上层的组成部分。
// 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(),它会构建一个新的商店,一切都很好。
谢谢你帮忙。
发布于 2017-10-26 10:17:09
您的当前代码无法工作,因为您要在index.js和helpers.js中创建单独的存储,而您应该使用相同的Redux存储。
您可以将存储初始化代码移动到单独的模块中,导出存储并导入到任何需要使用它的地方。
// 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());
}https://stackoverflow.com/questions/46951562
复制相似问题