如何使用next-redux-wrapper在nextjs页面之间共享状态?

3lxsmp7m  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(238)

我有这个主页

const Home: NextPage = () => { 
  return (<> <Link href='/2'><a>Go to page 2</a></Link> </>)
}

Home.getInitialProps = wrapper.getInitialPageProps(
  ({ dispatch }) =>
    async () => {
      await dispatch(addInitialSources('book'))
      await dispatch(addCategoriesMenu('book'))
    }
);
export default Home

注意调度的两个操作,这设置了整个应用程序的初始状态。
当我们转到[id]/index.tsx时,我需要商店的初始状态与从主页请求的状态相同。

const SecondPage: NextPage = () => { 
  return (<> <Link href='/'><a>Go Home</a></Link> </>)
}

SecondPage.getInitialProps = wrapper.getInitialPageProps(
  ({ dispatch }) =>
    async () => {
      await dispatch(addInitialSources('book'))
      await dispatch(addCategoriesMenu('book'))
    }
);
export default SecondPage

是否有一种方法可以调用/设置这些调度,而不是在每个页面上调用它们?
这是pages/_app.tsx设置(如果需要)。

import 'tailwindcss/tailwind.css';
import type { AppProps } from 'next/app'
import { wrapper } from "@store/store" 
function MyApp({ Component, pageProps }: AppProps) {
  return <Component {...pageProps} />
}
export default wrapper.withRedux(MyApp)
t1qtbnec

t1qtbnec1#

您可以使用getInitialProps在inside _app.tsx中调用它们,您应该注意到这将禁用自动静态优化。您在此处所做的调度将在每个页面请求上全局调度,并且在嵌套页面级别中可用。
示例代码来自https://github.com/kirill-konshin/next-redux-wrapper#app:


# pages/_app.tsx

import React from 'react';
import App, {AppInitialProps} from 'next/app';
import {wrapper} from '../components/store';
import {State} from '../components/reducer';

// Since you'll be passing more stuff to Page
declare module 'next/dist/next-server/lib/utils' {
    export interface NextPageContext {
        store: Store<State>;
    }
}

class MyApp extends App<AppInitialProps> {

    public static getInitialProps = wrapper.getInitialAppProps(store => async context => {

        store.dispatch({type: 'TOE', payload: 'was set in _app'});

        return {
            pageProps: {
                // https://nextjs.org/docs/advanced-features/custom-app#caveats
                ...(await App.getInitialProps(context)).pageProps,
                // Some custom thing for all pages
                pathname: ctx.pathname,
            },
        };

    });

    public render() {
        const {Component, pageProps} = this.props;

        return (
            <Component {...pageProps} />
        );
    }
}

export default wrapper.withRedux(MyApp);

相关问题