将 redux 与 redux-persist 与服务器端渲染一起使用

IT技术 javascript reactjs redux server-side-rendering redux-persist
2021-05-20 22:30:52

我正在尝试在 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 };
}

索引.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
);

事情仍然存在,并且在客户端的开发中没有发生,但是当我测试 SSR 时,应用程序会加载,然后重新加载并变为空白。它重新加载让我认为状态没有被相同的数据水合。此刻它完全崩溃让我感到困惑。

知道如何进行吗?

编辑

经过一些老式的调试后,我发现删除该<PersistGate loading={<Loader />} persistor={persistor}>行将允许应用程序最初加载,并且按预期通过服务器加载内容,但数据无法正确保留(显然)。

我使用PersistGate组件的方式有什么问题吗?

window.__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
}
3个回答

当您将 Redux-persist 与 SSR 一起使用时,它会导致崩溃,诸如它会显示白屏 1-5 秒然后显示页面之类的问题。

这是 Persist + Hydrate 的问题,要解决它,请尝试以下解决方案。:)

  1. 删除 Redux-persist。大声笑开个玩笑!
  2. 删除<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"));
   }
});

我在 NextJs 中使用了以下设置。

当窗口未定义(在服务器上)时,我渲染没有 PersistGate 的应用程序。

store 配置需要不占用存储,我根据传递的 prop 确定。

class MyApp extends App {
  public render() {
    const { Component, pageProps } = this.props;
    if (typeof window === "undefined") {
      const { store } = configureStore();
      return (
        <Provider store={store}>
          <Component {...pageProps} />
        </Provider>
      );
    }
    const { store, persistor } = configureStore(storage);

    return (
      <Provider store={store}>
        <PersistGate loading={null} persistor={persistor}>
          <Component {...pageProps} />
        </PersistGate>
      </Provider>
    );
  }
}

export default MyApp;
const configureStore = (passedStorage?: AsyncStorage | WebStorage) => {
  const combinedReducers = combineReducers({
    conjugations: conjugationReducer
  });
  if (!passedStorage) {
    const store = createStore(combinedReducers);
    return { store };
  }

  const persistConfig = {
    key: "root",
    storage: passedStorage
  };
  const persistedReducer = persistReducer(persistConfig, combinedReducers);

  const store = createStore(
    persistedReducer
  );
  const persistor = persistStore(store);
  return { store, persistor };
};

对我有用的一种解决方案如下 -

  • 在存储中定义所有操作和减速器 - 不使用任何 redux-persist。公开以 reducer 作为参数的 createStore 方法。
  • 在服务器上,导入 store 中定义的 reducer 并创建 store,renderToString()。
  • 在客户端,导入相同的 reducer,使用 'storage' 创建一个持久化的 reducer(请注意,'storage' 在服务器上不起作用,所以我们只能在客户端导入它)。此外,使用从服务器发送的 redux 状态和这个持久化的 reducer 创建存储。现在持久化这个存储并使用这个存储(在 Provider 中)和持久化器(在 PersistGate 中)

对我来说,如果我尝试保留的所有变量都是组件的一部分,那么它运行良好。您可以使用对服务器的后期调用来管理其他变量(在组件中使用 {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