我们正试图将NextJs项目从JS移到TS,而这样做的时候我遇到了以下问题。
我的_app.tsx中的getInitialProps如下所示:
static async getInitialProps({ router, ctx, Component }) {
const { req, isServer, store, res, query } = ctx;
let pageProps = {};
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx);
}
return { pageProps, isServer, router, store };
}
但是当我尝试访问诸如以下功能组件中的存储时:
SupportHome.getInitialProps = async ({ query, store, isServer }) => {
store.dispatch(getCategory());
return {
isServer,
store
};
};
它引发以下错误: 属性“ store”在类型“ NextPageContext”上不存在,属性“ isServer”在类型“ NextPageContext”上不存在 有人可以帮我吗?
答案 0 :(得分:2)
解决了该问题。基本上,NextPageContext在其界面中定义了以下字段:
export interface NextPageContext {
/**
* Error object if encountered during rendering
*/
err?: (Error & {
statusCode?: number;
}) | null;
/**
* `HTTP` request object.
*/
req?: IncomingMessage;
/**
* `HTTP` response object.
*/
res?: ServerResponse;
/**
* Path section of `URL`.
*/
pathname: string;
/**
* Query string section of `URL` parsed as an object.
*/
query: ParsedUrlQuery;
/**
* `String` of the actual path including query.
*/
asPath?: string;
/**
* `Component` the tree of the App to use if needing to render separately
*/
AppTree: AppTreeType
}
因此,我只是在_app.tsx中扩展了接口。像这样:
import {Store} from "redux";
export interface MyPageContext extends NextPageContext {
store: Store;
isServer: boolean;
}
现在,每当我必须在任何功能组件中使用getInitialProps时,我都会这样称呼它:
HelpDesk.getInitialProps = async (props: MyPageContext) => {
const { query, store } = props;
store.dispatch(getCategory());
return { query };
};
从here
汲取灵感答案 1 :(得分:0)
执行此操作以查看发生的情况:
SupportHome.getInitialProps = async (something) => {
console.log(something)
//store.dispatch(getCategory());
//return {
// isServer,
// store
//};
};
如果这是您所看到的,那么看起来您想要的属性就在props
子项上:
props: { err: xx, req: IncomingMessage { ...something }, res: ServerResponse { ...something }, pathname: '/ComponentName', query: {}, asPath: '/xyz/', AppTree: [Function: AppTree], store: { dispatch: [Function], subscribe: [Function: subscribe], getState: [Function: getState], replaceReducer: [Function: replaceReducer], runSagaTask: [Function], sagaTask: [Object], [Symbol(observable)]: [Function: observable] }, isServer: true }
您可能会将错误的对象传递给此函数,因此错误在上游。
SupportHome.getInitialProps = async ({props}) => {
console.log(props)
const { store, isServer, store } = props
store.dispatch(getCategory());
return {
isServer
store
};
};