在NextJS中的getServerSideProps中访问Redux存储

时间:2020-07-09 15:18:12

标签: reactjs redux react-redux next.js

我想在getServerSideProps()中访问我的redux存储;在我的Next.js应用中。我想拥有要存储在Redux Store中的用户ID,以便可以预加载用户数据。我现在正在使用next-redux-wrapper,并且在客户端运行。但是,当我在getServerSideProps()中访问商店时,它将返回初始状态。我检查了几个示例,但无法正常运行。

我的configureStore.js

import { createStore, applyMiddleware, compose } from "redux";
import reducer from "./../service";
import thunk from 'redux-thunk'
import { createWrapper, HYDRATE} from 'next-redux-wrapper';

const SET_CLIENT_STATE = 'SET_CLIENT_STATE';

const storeEnhancers = typeof window != 'undefined' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose

const makeStore = ({ isServer }) => {

  if (isServer) {

    return createStore(reducer, storeEnhancers(applyMiddleware(thunk)) );

  } else {

      const { persistStore, persistReducer } = require('redux-persist');
      const storage = require('redux-persist/lib/storage').default;

      const persistConfig = {
          key: 'nextjs',
          whitelist: ['userReducer'],
          storage
      };

      const store = createStore(
        persistReducer(persistConfig, reducer),
        storeEnhancers(applyMiddleware(thunk))
      );
  
      store.__PERSISTOR = persistStore(store);

      return store;
  }
};

export const wrapper = createWrapper(makeStore);

export const setClientState = (clientState) => ({
  type: SET_CLIENT_STATE,
  payload: clientState
});

我的_app.js:

import React from 'react';
import PropTypes from 'prop-types';
import Head from 'next/head';
import { ThemeProvider } from '@material-ui/core/styles';
import CssBaseline from '@material-ui/core/CssBaseline';
import theme from '../styles/theme';
import { useStore } from "react-redux";
import { PersistGate } from 'redux-persist/integration/react';
import {wrapper} from './../redux/configureStore';

const MyApp = ({Component, pageProps}) => {
  const store = useStore((state) => state);

  React.useEffect(() => {
    const jssStyles = document.querySelector('#jss-server-side');
    if (jssStyles) {
      jssStyles.parentElement.removeChild(jssStyles);
    }
  }, []);

  return (
    <React.Fragment>
      <Head>
        <title>Deeltuinen</title>
        <meta name="viewport" content="minimum-scale=1, initial-scale=1, width=device-width" />
      </Head>
        <PersistGate persistor={store.__PERSISTOR} loading={null}>
          <ThemeProvider theme={theme}>
            <CssBaseline />
            <Component {...pageProps} />
          </ThemeProvider>
        </PersistGate>
    </React.Fragment>
  );
}

export default wrapper.withRedux(MyApp);

MyApp.propTypes = {
  Component: PropTypes.elementType.isRequired,
  pageProps: PropTypes.object.isRequired
};

最后是我要获取存储状态的页面:

import React from 'react';
import Layout from './../../components/Layout';
import API from './../../service/api';
import {connect} from "react-redux";
import {wrapper, setClientState} from './../../redux/configureStore';

const AccountSettings = ({data}) => {
 
  return (
    <Layout title="Deeltuinen">
      // User form
    </Layout>
  );
}

export const getServerSideProps = wrapper.getServerSideProps(
  ({store, req, res}) => {
    const state = store.getState();
    console.log(state);

    //const data = await API.getUser(state.userReducer.user.token);
  }
);

export default connect(state => state,{setClientState})(AccountSettings);

2 个答案:

答案 0 :(得分:1)

我的代码:

export const getServerSideProps = wrapper.getServerSideProps(async ({ req, res, store }) => {
  const state = store.getState();
  console.log('state', state);

  return {
    props: {},
  };
});
`

答案 1 :(得分:0)

如果需要将一些参数传递给getServerSideProps,则应设置页面结构来实现。

示例:

如果我需要从用户那里获得一些荣誉,并且我的api需要使用“ userId”参数,则可以这样设置我的页面:

pages/credits/[userId].js

这样,我可以通过以下方式访问getServerSideProps函数中的userId参数:

export async function getServerSideProps (context) {

   const { userId } = context.params
   
   ...
   // API call to get the Credits by userId
}