Easy-Peasy / NextJS / React maybeGetServerSnapshot不是函数

qojgxg4l  于 2023-04-30  发布在  React
关注(0)|答案(1)|浏览(129)

运行最新的easy-peasy(5.2.0)沿着NextJS的最新主要版本(12.1.6)和React(18.1.0)导致easy-peasy抛出错误

TypeError: maybeGetServerSnapshot is not a function` when calling their native `useStoreState`.
export default function Counter() {
> 4 |   const count = useStoreState((state) => state.counter.count);
    |                               ^
  5 |   const increment = useStoreActions((actions) => actions.counter.increment);

经过大量的寻找,我没有发现其他关于这个问题的帖子,虽然我看到类似的问题与其他存储选项,如zustand https://github.com/pmndrs/zustand/issues/963,虽然这似乎是一个红鲱鱼。
我面临的错误似乎是一个内部NextJS的问题,他们的存储同步从easy-peasyReact,但在一天结束时,这个错误并没有返回很多信息,我很卡住。
这个使用NextJS和easy-peasy的例子在很多地方都被引用过,并且在https://codesandbox.io/s/c24rg上工作得很好。但是,此项目分别使用每个项目的最后一个主要版本。我有一个严格的要求,那就是保持在我指定的主要版本或React和Next。对这个问题的任何深入了解都会有很大的帮助。
编辑1:
添加SSR状态

export function getServerSideProps() {
    const store = initializeStore()

    const data = ['apple', 'pear', 'orange', 'nuts']
    store.getActions().inventory.setItems(data)

    return {
        props: {
            ssrStoreState: store.getState()
        }
    }
}

初始化客户端状态

export default function WrappedApp({ Component, pageProps }) {
    const store = useStore(pageProps.ssrStoreState)

    return (
        <StoreProvider store={store}>
            <Component {...pageProps} />
        </StoreProvider>
    )
}

使用状态效应获取数据

import { useStoreState, useStoreActions } from "easy-peasy";

export default function Counter() {
  const count = useStoreState((state) => state.counter.count);
  const increment = useStoreActions((actions) => actions.counter.increment);

  return (
    <div style={{ margin: "2rem" }}>
      <h1>Counter</h1>
      <p>value = {count}</p>
      <button onClick={increment}>Increment counter</button>
    </div>
  );
}

用于SSR到客户端同步的自定义存储示例化在store/store文件中找到

function initStore(preloadedState = initialState) {
    return createStore(
        persist(
            storeModel,
            { allow: ['shop'] }
        ),
        { initialState: preloadedState }
    )
}

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
}

export function useStore(initialState) {
    const store = useMemo(() => initializeStore(initialState), [initialState])
    return store
}

相关问题