我正在开发一个简单的next.js应用程序。对于状态管理,我使用下一个redux包装器。在我的主页中,我想使用store.dispatch
从我的api中获取数据库中的所有房间。
当我使用getServerSideProps
并调度一个它有效的操作时,它会获取我所有的房间。但问题是,当我想用getStaticProps
取房间时,它不起作用,什么都没发生。
当我开发大型应用程序时,我应该使用下一个redux包装器吗?还是应该尝试其他库。因为我想在我的应用程序中使用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;
使用7.0.x版本。npm install next-redux-wrapper
,默认安装6.0.x
这仅在7及以上版本的下一个redux包装中得到支持