在React Component之外访问Redux Store返回初始值

时间:2019-08-22 23:14:08

标签: javascript reactjs redux react-redux redux-persist

在基于Keftaa/expo-redux-boilerplate boilerplate且使用redux-persist的React Redux应用程序中,我们如何从非React组件访问持久化的Redux存储?

问题:我不确定如何访问/导出store返回的configureStore(),因为configureStore()被传递了{{1} }函数,更重要的是,它存储在setState()组件的状态中而不导出:

/src/boot/setup.js

Setup

/src/boot/configureStore.js

export default class Setup extends Component {

    this.state = {
      isLoading: false,
      store: configureStore(() => this.setState({ isLoading: false })),
      isReady: false
    };

    ...


  render() {
    if (!this.state.isReady || this.state.isLoading) {
      return <Expo.AppLoading />;
    }
    return (
        <Provider store={this.state.store}>
          <App />
        </Provider>
    );
  }
}

尝试失败

仅返回其import { AsyncStorage } from "react-native"; import devTools from "remote-redux-devtools"; import { createStore, applyMiddleware, compose } from "redux"; import thunk from "redux-thunk"; import { persistStore, persistReducer } from "redux-persist"; import reducer from "../reducers"; import devToolsEnhancer from 'remote-redux-devtools'; import storage from 'redux-persist/lib/storage' // defaults to localStorage for web and AsyncStorage for react-native const persistConfig = { key: 'root', storage, } const persistedReducer = persistReducer(persistConfig, reducer); export default function configureStore(onCompletion: () => void): any { const enhancer = compose( applyMiddleware(thunk), devTools({ name: "MyApp", realtime: true }) ); let store = createStore(persistedReducer, enhancer); let persistor = persistStore(store, null, onCompletion); return store; } 的商店。我相信这是因为我们正在创建一个新的redux存储,而不是从initialValues导入原始存储。

我的 /src/lib/utils.js

setup.js

使用

  • import configureStore from "../boot/configureStore"; const state = configureStore console.log(state); // returns only the initial value for the store
  • react@16.8.3
  • redux@4.0.4
  • react-redux@7.1.0

1 个答案:

答案 0 :(得分:1)

您可以从COPY组件中导出商店访问器功能,例如:

COPY

然后从其他地方调用Setup,并在调用 let store = null; export function getStore() { return store; } export default class Setup extends Component { constructor(props) { super(props); store = configureStore(() => this.setState({ isLoading: false })), this.state = { isLoading: false, store, isReady: false }; } 之前进行检查以确保其不为空;