Javascript 访问React组件外部的Redux存储返回初始值
在使用Javascript 访问React组件外部的Redux存储返回初始值,javascript,reactjs,redux,react-redux,redux-persist,Javascript,Reactjs,Redux,React Redux,Redux Persist,在使用Redux persist的基于的React-Redux应用程序中,我们如何从非React组件访问持久化Redux存储 问题:我不确定如何访问/导出由configureStore()返回的store,因为configureStore()传递了一个setState()函数,更重要的是,它存储在Setup组件的状态中,并且没有导出: export default class Setup extends Component { this.state = { isLoadi
Redux persist
的基于的React-Redux应用程序中,我们如何从非React组件访问持久化Redux存储
问题:我不确定如何访问/导出由configureStore()
返回的store
,因为configureStore()
传递了一个setState()
函数,更重要的是,它存储在Setup
组件的状态中,并且没有导出:
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存储,而不是从setup.js
导入原始的redux存储
我的/src/lib/utils.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
反应-redux@7.1.0
redux-persist@5.10.0
设置
组件导出存储访问器功能,例如:
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()
,并在调用store.getState()
之前检查以确保它不为null