【问题标题】:Using getStaticProps with next-redux-wrapper将 getStaticProps 与 next-redux-wrapper 一起使用
【发布时间】:2021-09-01 07:49:34
【问题描述】:

我正在开发一个简单的 next.js 应用程序。对于状态管理,我使用的是 next-redux-wrapper。在我的主页中,我想使用 store.dispatch 从我的 api 获取数据库中的所有房间。

当我使用getServerSideProps 并调度它起作用的操作时,它会获取我所有的房间。但问题是当我想用getStaticProps 获取房间时,它不起作用,什么也没发生。

我应该在开发大型应用程序时使用 next-redux-wrapper 还是应该尝试其他库。因为我想在我的应用程序中使用getStaticPathsgetStaticPropsgetServerSideProps。在这些函数中,我通常会调度一个 redux 操作。

Store.js 文件

import { createStore, applyMiddleware } from "redux";
import { HYDRATE, createWrapper } from "next-redux-wrapper";
import thunkMiddleware from "redux-thunk";
import reducers from "./reducers/reducers";

const bindMiddleware = (middleware) => {
 if (process.env.NODE_ENV !== "production") {
 const { composeWithDevTools } = require("redux-devtools-extension");
 return composeWithDevTools(applyMiddleware(...middleware));
 }
 return applyMiddleware(...middleware);
};

const reducer = (state, action) => {
 if (action.type === HYDRATE) {
 const nextState = {
 ...state,
 ...action.payload,
 };
 return nextState;
 } else {
 return reducers(state, action);
 }
};

const initStore = () => {
 return createStore(reducer, bindMiddleware([thunkMiddleware]));
};

export const wrapper = createWrapper(initStore);

_app.js 文件

import "../styles/globals.css";
import { wrapper } from "../redux/store";

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

export default wrapper.withRedux(MyApp);

pages/index.js 文件

import Layout from "../components/layout/Layout";
import Home from "../components/Home";
import { getRooms } from "../redux/actions/roomActions";
import { wrapper } from "../redux/store";

function HomePage() {
 return (
 <Layout>
 <Home />
 </Layout>
  );
}


//THIS WORKS
/*export const getServerSideProps = wrapper.getServerSideProps(
  (store) =>
    async ({ req }) => {
      await store.dispatch(getRooms(req));
    }
);*/
// THIS WORKS


// THIS DOES NOT WORK
export const getStaticProps = wrapper.getStaticProps(({ store }) => {
 async () => {
 await store.dispatch(getRooms("http://localhost:3000/"));
 };
});
// THIS DOES NOT WORK

export default HomePage;

【问题讨论】:

  • @Ashok 它没有帮助。
  • 你不应该在wrapper.getStaticProps调用中解构store变量,应该是wrapper.getStaticProps((store) =&gt; {而不是像你在wrapper.getServerSideProps中那样。

标签: reactjs redux react-redux next.js next-redux-wrapper


【解决方案1】:

使用 7.0.x 版本。 npm install next-redux-wrapper,默认安装6.0.x

而且只有 7 及以上版本的 next-redux-wrapper 才支持此功能

【讨论】:

    猜你喜欢
    • 2022-10-14
    • 2020-08-10
    • 2020-05-16
    • 2021-11-06
    • 2021-01-16
    • 2018-06-04
    • 2021-10-05
    • 2021-11-18
    • 2019-11-10
    相关资源
    最近更新 更多