Gur*_*bot 5 javascript reactjs redux server-side-rendering redux-persist
我正在尝试在SSR应用程序中使用redux-persist 5.10.0实现redux 4.0.0,并且遇到一个问题,在该问题中,createStore()
如果应用程序崩溃,我将无法正确提供预加载状态。
发生的情况是应用程序从服务器加载了初始状态,但是当应用程序尝试createStore()
在客户端上预加载状态时,应用程序刷新并崩溃。我以为是因为我的preloadedState格式不正确?
但是我不确定,因为在控制台,UI,nada中没有收到任何错误消息。
这是一些相关的代码:
商店/index.js
export default function configureStore(preloadedState = {}) {
// This will store our enhancers for the store
const enhancers = [];
// Add thunk middleware
const middleware = [thunk];
// Apply middlware and enhancers
const composedEnhancers = compose(
applyMiddleware(...middleware),
...enhancers
);
// Set up persisted and combined reducers
const persistedReducer = persistReducer(persistConfig, rootReducer);
// Create the store with the persisted reducers and middleware/enhancers
const store = createStore(persistedReducer, preloadedState, composedEnhancers);
const persistor = persistStore(store, null, () => {
store.getState(); // if you want to get restoredState
});
return { store, persistor };
}
Run Code Online (Sandbox Code Playgroud)
index.js
const preloadedState = window.__PRELOADED_STATE__ ? window.__PRELOADED_STATE__ : {};
delete window.__PRELOADED_STATE__;
// Create redux store
const { persistor, store } = configureStore(preloadedState);
// Get app's root element
const rootEl = document.getElementById("root");
// Determine if we should use hot module rendering or DOM hydration
const renderMethod = !!module.hot ? ReactDOM.render : ReactDOM.hydrate;
renderMethod(
<Provider store={store}>
<PersistGate loading={<Loader />} persistor={persistor}>
<BrowserRouter>
<App />
</BrowserRouter>
</PersistGate>
</Provider>,
rootEl
);
Run Code Online (Sandbox Code Playgroud)
事情仍然存在,并且在客户端上尚无进展,但是当我测试SSR时,应用会加载,然后重新加载并变为空白。重新加载使我认为状态不会因相同的数据而变得水合。现在它完全崩溃让我感到困惑。
关于如何进行的任何想法?
编辑
经过一些老式的调试后,我发现删除该<PersistGate loading={<Loader />} persistor={persistor}>
行将使该应用程序最初可以加载,并且可以按预期的那样通过服务器加载内容,但是数据不能正确保存(显然)。
我如何使用PersistGate
组件有什么问题吗?
窗口。__PRELOADED_STATE__
{
user: {…}, banners: {…}, content: {…}, locations: {…}, news: {…}, …}
banners: {isLoading: 0, banners: Array(2)}
content: {isLoading: 0, errors: {…}, data: {…}}
locations: {countries: Array(0), provinces: Array(0), default_country: null, isLoading: false, error: null, …}
news: {isLoading: 0, hasError: 0}
phoneTypes: {isLoading: false}
profileStatuses: {isLoading: false}
profileTypes: {isLoading: false}
reviewers: {isLoading: false}
route: {}
salutations: {isLoading: false}
sectors: {isLoading: false, sectors: Array(0)}
siteInfo: {pageTitle: "", isLoading: 0, hasError: 0, error: "", site: {…}, …}
sort: {value: "", dir: ""}
user: {isLoading: false, loginChecked: {…}, admin: null, reviewer: null, loginTokenLoading: false, …}
_persist: {version: -1, rehydrated: true}
__proto__: Object
}
Run Code Online (Sandbox Code Playgroud)
当您将 Redux-persist 与 SSR 一起使用时,它会导致崩溃,诸如它会显示白屏 1-5 秒然后显示页面之类的问题。
这是 Persist + Hydrate 的问题,要解决它,请尝试以下解决方案。:)
<PersistGate>
并使用如下代码代码
function Main() {
return (
<Provider store={store}>
// Don't use <PersistGate> here.
<Router history={history}>
{ Your other code }
</Router>
</Provider>
);
}
persistor.subscribe(() => {
/* Hydrate React components when persistor has synced with redux store */
const { bootstrapped } = persistor.getState();
if (bootstrapped) {
ReactDOM.hydrate(<Main />, document.getElementById("root"));
}
});
Run Code Online (Sandbox Code Playgroud)
对我有用的一种解决方案如下 -
对我来说,如果我试图保留的所有变量都是组件的一部分,那么效果会很好。您可以使用对服务器的后调用来管理其他变量(在组件中使用 {axios})。
检查此存储库以在没有 redux-persist 的情况下创建存储 - 之后按照上述步骤操作 - https://github.com/alexnm/react-ssr/tree/fetch-data
// in client.js
import {createStore as createPersistedStore} from 'redux';
import createStore, { reducers } from './store';
const persistConfig = {
key: 'app',
storage,
}
const persistedReducers = persistReducer(persistConfig, reducer);
// creating a persisting store in client.js only
const store = createStore(persistedReducers, window.REDUX_DATA);
const persistor = persistStore(store);
const jsx = (
<ReduxProvider store={store}>
<PersistGate loading={"loading from store"} persistor={persistor}>
<Router>
<App />
</Router>
</PersistGate>
</ReduxProvider>
);
const app = document.getElementById("app");
ReactDOM.hydrate(jsx, app);
// end client.js
// in server.js - only see createStore as well as const jsx object, and a dummy context
import createStore, { reducers } from './store';
const app = express()
app.get( "/*", (req, res, next) => {
const context = {};
// not created using persisted store in the server - don't have to
const store = createStore(reducer);
// define data with the routes you need (see the github repo)
Promise.all(data).then(() => {
const jsx = (
<ReduxProvider store={store}>
<StaticRouter context={context} location={req.url}>
<App />
</StaticRouter>
</ReduxProvider>
);
const reactDom = renderToString(jsx);
const reduxState = store.getState();
// more code for res.end
});
});
// end server.js
// in store.js
import {createStore, combineReducers, applyMiddleware} from "redux";
// your actions and reducers
export const reducer = combineReducers({
// reducers
)};
export default (reducerArg, initialState) =>
createStore(reducerArg,initialState);
// end store.js
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
819 次 |
最近记录: |