关于javascript:在React Component之外访问Redux Store返回初始值

Accessing Redux Store outside of React Component returns initial Values

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

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

/src/boot/setup.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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>
    );
  }
}

/src/boot/configureStore.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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;
}

尝试失败

仅返回其initialValues返回商店。我相信这是因为我们正在创建一个新的redux存储,而不是从setup.js

导入原始存储。

我的/src/lib/utils.js

1
2
3
4
import configureStore from"../boot/configureStore";

const state = configureStore
console.log(state);  // returns only the initial value for the store

使用


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
      };
}

然后从其他位置调用getStore()并检查以确保其不为null,然后再调用store.getState();