I have problem with redux store in SSR react app. Everything working great, initialState creating on server received by window.initialState on client. Problem starting when I whant to get current store by store().getState in my App.js
createStore.js
const configureStore = preloadedState => {
const store = createStore(
rootReducer,
preloadedState || global.__initialData__,
applyMiddleware(
promiseMiddleware(),
thunk,
// logger
)
);
if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept('./reducers', () => {
const nextRootReducer = require('./reducers/index');
store.replaceReducer(nextRootReducer);
});
}
return store;
}
export default configureStore;
server.js
const stores = createStore( reducers );
stores.dispatch(setLang( serve_lang )); // 'pl'
global.__initialData__ = stores.getState();
let initialDatas = stores.getState();
const store = configureStore( initialDatas );
...
<html>
<script>window.__initialData__ = ${serialize(initialDatas)}</script>
...
client.js
const store = configureStore(window.__initialData__);
hydrate(
<Provider store={store} key={Math.random()}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>,
document.getElementById('root')
);
if (module.hot) {
module.hot.accept();
}
and in my App.js I want to get my current store by
import store from 'configureStore'l
store().getState();
and I always have initialState when I do store.getState() in App.js
and I always have initialState when I do store.getState() in App.js
You are creating a new store instance. That won't be modified because the rest of your components use another one you have created in client.js
import store from 'configureStore'l
store().getState(); // this is new store not the one you have passed to Provider
What you could do is to pass first store instance to App inside client.js
using properties.
const store = configureStore(window.__initialData__);
hydrate(
<Provider store={store} key={Math.random()}>
<BrowserRouter>
<App store={store}/>
</BrowserRouter>
</Provider>,
document.getElementById('root')
Or access it via context ( Provider
actually put its store to the context so that inner "connected" components could access it). You could read about context here. Docs .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.