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

Redux getState不起作用,但useSelector起作用,redux,redux-persist,Redux,Redux Persist,已解决 我们在发帖两分钟后发现了一个问题。。。 我们的解决方案是: let state:any; store.subscribe(() => { state = store.getState(); }); 我正在用Redux和Redux persist构建一个React应用程序。我在访问React组件外部的Redux状态时遇到问题。如果我订阅存储和控制台日志状态,它将显示正确的状态,其中包含数据,但当我在控制台日志外部记录状态时(const state=store.getStat

已解决

我们在发帖两分钟后发现了一个问题。。。 我们的解决方案是:

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钩子时,它工作得很好。这是一个非常奇怪的bug,因为它是在我使用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};


你的问题描述似乎有点奇怪。您需要在哪里以及如何访问React之外的Redux商店?而列出的解决方案似乎非常错误。将
state
声明为订阅回调之外的变量不应影响行为,因为
getState()
始终返回对当前状态值的引用。您能在实际尝试中添加更多的细节吗?如何,为什么?我们需要访问状态OutStand的反应来比较WebSoCube消息与ReDux中的当前状态,看看我们是否需要发送消息,因为否则它将每秒发送到ReDux。这是在Redux中使用WebSocket的一般推荐位置,并且它还可以访问
getState