[英]React Redux - accessing existing store in a helper function
我試圖將商店實例(商店狀態)放在反應組件之外,即在單獨的幫助器函數中。 我有我的減速機,我的動作,我在最上面的組件中創建了一個商店。
// 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(),它會構建一個新的商店,一切正常。
感謝幫助。
您當前的代碼無法正常工作,因為您要在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());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.