如何使用Next-Redux包装器在Next.js(Typescript)中使用SSR和Redux



在Next.js(Typescript(中使用redux和SSR,使用下一个redux包装器,但在这一行上出错

异步({req,store}(

说,键入"Promise"不提供签名匹配项(上下文:GetServerSidePropsContext<ParsedUrlQuery,PreviewData>(:Promise<GetServerSidePropsResult<{[key:string]:任意;}>gt

类型"Store<"上不存在属性"req";空对象&{filterReducer:never;},any>amp;{dispatch:unknown;}'

类型"store<"上不存在属性"store";空对象&{filterReducer:never;},any>amp;{调度:未知;}'

这是我的SSR代码:-

export const getServerSideProps: GetServerSideProps = wrapper.getServerSideProps(async ({ req, store }) => {

let { query } = req
let searchCategory = query.category?.toString().toLowerCase().replace(/ /g, "-");
const apolloClient = initializeApollo();
const response = await apolloClient.query({
query: GET_PRODUCT_BY_CATEGORY,
variables: {
numProducts: 10,
category: searchCategory
}
});
await store.dispatch(getProducts(response));

}); 

您调用wrapper.getServerSideProps的方式不对。

尝试如下:

export const getServerSideProps = wrapper.getServerSideProps(
store => async ({req, res, query}) => {
// do your stuff with store and req
}
);

如果你正在寻找一个工作演示,你可以访问我的旧答案

这个代码库可以帮助您。("下一个":"10.1.3"(请尝试使用getInitialProps而不是getServerSideProps。这对我来说是有效的。类似以下代码:

尝试在_app.js 中

import { wrapper } from '/store';
function MyApp(props) {
const { Component, pageProps } = props;
...
return (
<Component {...pageProps} />
)
}
App.getInitialProps = async props => {
const { Component, ctx } = props;
const pageProps = Component.getInitialProps
? await Component.getInitialProps(ctx)
: {};
//Anything returned here can be accessed by the client
return { pageProps: pageProps, store: ctx.store };
};
export default wrapper.withRedux(App);

store.js文件:

const makeStore = props => {
if (!isEmpty(props)) {
return createStore(reducer, bindMiddleware([thunkMiddleware]));
} else {
const { persistStore, persistReducer } = require('redux-persist');
const persistConfig = {
key: 'root',
};
const persistedReducer = persistReducer(persistConfig, reducer); // Create a new reducer with our existing reducer
const store = createStore(
persistedReducer,
bindMiddleware([thunkMiddleware])
); // Creating the store again
store.__persistor = persistStore(store); // This creates a persistor object & push that persisted object to .__persistor, so that we can avail the persistability feature
return store;
}
};
// Export the wrapper & wrap the pages/_app.js with this wrapper only
export const wrapper = createWrapper(makeStore);

在您的页面中:

HomePage.getInitialProps = async ctx => {
const { store, query, res } = ctx;
};

相关内容

  • 没有找到相关文章

最新更新