首页 > 解决方案 > React SSR - redux-persist 无法创建同步存储

问题描述

我尝试使用 redux-persist 包我收到此错误:redux-persist 无法创建同步存储。回退到 noop 存储。

我正在对服务器做出反应。

反应版本:17.0.2 - react-redux 版本:7.2.4 - redux 版本:4.1.0 - redux-persist 版本:6.0.0

商店.js:

import { createStore, combineReducers, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import { composeWithDevTools } from 'redux-devtools-extension'
import { productListReducer } from './reducers/productReducers'
import { categoryListReducer } from './reducers/categoryReducers'
import { persistStore, persistReducer } from 'redux-persist'
import storage from 'redux-persist/lib/storage'

const reducer = combineReducers({
    productList: productListReducer,
    categoryList: categoryListReducer,
})

const initialState = {}

const middleware = [thunk]

const persistConfig = {
    key: 'root',
    storage: storage,
}

const persistedReducer = persistReducer(persistConfig, reducer)


export let store = createStore(persistedReducer, composeWithDevTools(applyMiddleware(...middleware)))
export let persistor = persistStore(store)

index.js:

import React from 'react'
import { Provider } from 'react-redux'
import { hydrate } from 'react-dom'
import { BrowserRouter } from 'react-router-dom'
import { store } from './store'
import { persistor } from './store'
import './index.css'
import App from './App'
import reportWebVitals from './reportWebVitals'
import { PersistGate } from 'redux-persist/integration/react'

hydrate(
  <Provider store={store}>
    <PersistGate loading={null} persistor={persistor}>
      <BrowserRouter>
        <App />
      </BrowserRouter>
    </PersistGate>
  </Provider>,
  document.getElementById('root')
);

reportWebVitals()

frontend/server.js用于在服务器上进行渲染反应

import path from 'path'
import fs from 'fs'
import express from 'express'
import React from 'react'
import { StaticRouter } from 'react-router'
import ReactDOMServer from 'react-dom/server'
import { Provider } from 'react-redux'
import { store } from '../src/store'
import { persistor } from '../src/store'
import App from '../src/App'
import { createProxyMiddleware } from 'http-proxy-middleware'
import { PersistGate } from 'redux-persist/integration/react'

const PORT = 3000
const app = express()

app.use('/api/products', createProxyMiddleware({ target: 'http://198.51.100.255:5000', changeOrigin: true }))
app.use('/api/categories', createProxyMiddleware({ target: 'http://198.51.100.255:5000', changeOrigin: true }))

const router = express.Router()

const serverRenderer = (req, res, next) => {
  app.get('/*', function (req, res) {
    res.sendFile(path.join(__dirname, '../build/index.html'), function (err) {
      if (err) {
        res.status(500).send(err)
      }
    })
  })

  const context = {}

  fs.readFile(path.resolve('./build/index.html'), 'utf8', (err, data) => {
    if (err) {
      console.error(err)
      return res.status(500).send('An error occurred')
    }
    return res.send(
      data.replace(
        '<div id="root"></div>',
        `<div id="root">
        ${ReactDOMServer.renderToString(
          <Provider store={store}>
            <PersistGate loading={null} persistor={persistor}>
              <StaticRouter location={req.url} context={context}>
                <App />
              </StaticRouter>
            </PersistGate>
          </Provider>
        )}
        </div>`
      )
    )
  })
}

router.use('^/$', serverRenderer)

router.use(
  express.static(path.resolve(__dirname, '..', 'build'))
)

app.use(router)

app.listen(PORT, () => {
  console.log(`SSR running on port ${PORT}`)
})

标签: reactjsreduxreact-reduxserver-side-renderingredux-persist

解决方案


推荐阅读