React Redux - 在辅助函数中访问现有存储 [英] React Redux - accessing existing store in a helper function

查看:24
本文介绍了React Redux - 在辅助函数中访问现有存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 React 组件之外获取存储实例(存储状态),即在单独的辅助函数中.我有我的reducer,我的action,我在最上层的组件中创建了一个store.

I'm trying to get the store instance (store state) outside a react component, namely in a separate helper function. I have my reducer, my action, I have created a store in the most upper component.

// 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() 它会构建一个新的存储并且一切正常.

This approach is not working as console.log(store.getState()) returns undefined. However, if I pass an initialConfig to configStore() it builds a new store and everything works just fine.

感谢您的帮助.

推荐答案

您当前的代码不起作用,因为您正在将单独的存储创建到 index.jshelpers.js 而你应该使用相同的 Redux 存储.

Your current code is not working because you're creating separate stores into index.js and helpers.js while you should use same Redux store.

您可以将商店初始化代码移动到单独的模块中,导出商店并将其导入到您需要使用的任何地方.

You can move store initialization code into separate module, export store and import it whereever you need to use it.

// 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());
}

这篇关于React Redux - 在辅助函数中访问现有存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆