NextJS商店访问

时间:2019-12-18 16:16:08

标签: next redux-persist

我正在运行带有redux-persist(6.0.0)的nextjs(9.1.1)应用程序,但是我似乎无法访问商店中的数据

store.js-在这里,我只是设置一个函数来获取商店对象

export const appStore = (initialState = {}) => {

    const appliedMiddleware = process.env.NODE_ENV === 'production' ? applyMiddleware(thunkMiddleware) : composeWithDevTools(applyMiddleware(thunkMiddleware));

    const isClient = typeof window !== 'undefined';

    let store;

    if(isClient) {
        const { persistReducer } = require('redux-persist');
        const storage = require('redux-persist/lib/storage').default;
        const persistConfig = {
            key: 'root',
            storage,
            whitelist: ['config'],
        };

        store = createStore(
            persistReducer(persistConfig, RootReducer),
            initialState,
            appliedMiddleware
        );

        store.__PERSISTOR = persistStore(store);
    }
    else {
        store = createStore(RootReducer, initialState, appliedMiddleware);
    }

    return store;

};

const Store = appStore();

export const GetState = (store=null) => {
    const state = Store.getState();
    return state[store] !== undefined ? state[store] : state;
};

_app.js-在这里,我向商店调度了一些常规信息,例如主机和播放器的IP地址

class MyApp extends App {

    static async getInitialProps({ Component, ctx }) {

        if(ctx.req) {
            await ctx.store.dispatch(UpdateConfigAction(GetHeaderInfo(ctx.req)));
        }

        return {
            pageProps: Component.getInitialProps ? await Component.getInitialProps(ctx) : {}
        };
    }

    render() {

        const { Component, pageProps, store } = this.props;

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

}

这很好,我实际上可以在本地存储(客户端)上看到数据

index.js-在这里,我只是尝试从商店中读取

class Home extends React.Component {
    render() {
        console.log(GetState());
        ...
    }
}

因此,当用户首次进入应用程序时,我设法获取信息并进行存储。 问题是,即使它在本地存储上,我也无法访问它,它只是空的。 但是,如果我强制刷新(F5),则会显示该信息。

0 个答案:

没有答案