جافاسكريبت - React Redux - الوصول إلى المخزن الموجود في دالة مساعدة
أحاول الحصول على نسخة المتجر (حالة المتجر) خارج مكون 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()) يُرجع undefined. ومع ذلك، إذا قمت بتمرير initialConfig إلى configStore() فإنه يبني متجرًا جديدًا وتعمل كل الأمور بشكل جيد.
شكراً على المساعدة.
الإجابة رقم 1
الكود الحالي الخاص بك لا يعمل لأنك تقوم بإنشاء مخازن منفصلة في 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());
}
