我试图在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() 它会构建一个新商店并且一切正常。
感谢帮助。