【发布时间】:2021-09-01 07:49:34
【问题描述】:
我正在开发一个简单的 next.js 应用程序。对于状态管理,我使用的是 next-redux-wrapper。在我的主页中,我想使用 store.dispatch 从我的 api 获取数据库中的所有房间。
当我使用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);
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) => {而不是像你在wrapper.getServerSideProps中那样。
标签: reactjs redux react-redux next.js next-redux-wrapper