Redux getState不起作用,但useSelector起作用

时间:2020-01-29 12:35:43

标签: redux redux-persist

已解决

我们在发布此问题两分钟后发现了一个字面意思... 我们的解决方案是这样:

let state:any;
store.subscribe(() => {
    state = store.getState();
});

我正在使用Redux和redux-persist构建一个React应用。我在React组件外部访问Redux状态时遇到问题。如果我订阅了商店并进行控制台日志记录,则该状态将显示其中包含数据的正确状态,但是当我进行控制台日志记录时,在外部(const state = store.getState(); )进行记录的状态下,订阅箭头功能(store.subscribe(() => console.log(store.getState())))将其中的数据商店是空的。当我在React组件内部使用useSelector挂钩时,它可以正常工作。这是一个非常奇怪的错误,因为它是在我使用React组件外的商店编写代码后两周出现的。有人有类似的错误吗?

这是我的Redux配置。

// Redux.
import { createStore, applyMiddleware, compose } from "redux";

// Redux-thunk.
import thunk from "redux-thunk";

// Reducers.
import reducers from "../reducers";

// Storage.
import { persistStore, persistReducer } from 'redux-persist'
import storage from 'redux-persist/lib/storage' // defaults to localStorage for web

const persistConfig = {
    key: 'root',
    storage,
}
const persistedReducer = persistReducer(persistConfig, reducers);
const composeEnhancers =
    (window["__REDUX_DEVTOOLS_EXTENSION_COMPOSE__"] as typeof compose) ||
    compose;
const middleWare = applyMiddleware(thunk);
const store = createStore(persistedReducer,  composeEnhancers(middleWare));
const persistor = persistStore(store)

export {store, persistor};

0 个答案:

没有答案