Dav*_*idN 5 javascript store reactjs react-redux
我试图将商店实例(商店状态)放在反应组件之外,即在单独的帮助器函数中.我有我的减速机,我的动作,我在最上面的组件中创建了一个商店.
// 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());
}Run Code Online (Sandbox Code Playgroud)
这种方法不起作用,因为console.log(store.getState())返回undefined.但是,如果我将initialConfig传递给configStore(),它会构建一个新的商店,一切正常.
感谢帮助.
您当前的代码无法正常工作,因为您要创建单独的存储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());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3462 次 |
| 最近记录: |