我正在开发一个简单的 next.js 应用程序。对于状态管理,我使用的是 next-redux-wrapper。在我的主页中,我想使用store.dispatch
.
当我使用getServerSideProps
和调度一个动作时,它会获取我所有的房间。但问题是当我想用它来取房间时,getStaticProps
什么都没有发生。
我应该在开发大型应用程序时使用 next-redux-wrapper 还是应该尝试其他库。因为我想在我的应用程序中使用getStaticPaths
,getStaticProps
和getServerSideProps
。在这些函数中,我通常会发送一个 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);
页面/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;