【发布时间】:2021-07-14 18:55:10
【问题描述】:
我需要将 redux 与现有的下一个项目集成。但目前,我不明白商店是如何在服务器端工作的。
我正在关注这个例子:
https://github.com/vercel/next.js/blob/canary/examples/with-redux/pages/ssg.js
export const initializeStore = (preloadedState) => {
let _store = store ?? initStore(preloadedState)
// After navigating to a page with an initial Redux state, merge that state
// with the current state in the store, and create a new store
if (preloadedState && store) {
_store = initStore({
...store.getState(),
...preloadedState,
})
// Reset the current store
store = undefined
}
// For SSG and SSR always create a new store
if (typeof window === 'undefined') return _store
// Create the store once in the client
if (!store) store = _store
return _store
}
为什么要在服务端创建一个store,我问是因为在客户端也是这样创建的,最后用的是什么store。
如果在客户端创建了另一个完全不同的商店,为什么我需要在服务器中创建一个商店?
import { Provider } from 'react-redux'
import { useStore } from '../store'
export default function App({ Component, pageProps }) {
const store = useStore(pageProps.initialReduxState)
return (
<Provider store={store}>
<Component {...pageProps} />
</Provider>
)
}
下面的组件定义也在客户端渲染?
export function useStore(initialState) {
const store = useMemo(() => initializeStore(initialState), [initialState])
return store
}
【问题讨论】:
标签: javascript reactjs redux react-redux next.js