Búsqueda de sitios web

typescript - La propiedad 'store' no existe en el tipo 'NextPageContext'


Estamos intentando trasladar nuestro proyecto de NextJs de JS a TS y, al hacerlo, me encontré con el siguiente problema.

getInitialProps en mi _app.tsx va algo así:

    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 };
  }

Pero cuando intento acceder a la tienda en un componente funcional como:

SupportHome.getInitialProps = async ({ query, store, isServer }) => {
  store.dispatch(getCategory());
  return {
    isServer,
    store
  };
};

Lanza el siguiente error: La propiedad 'store' no existe en el tipo 'NextPageContext' y la propiedad 'isServer' no existe en el tipo 'NextPageContext'. ¿Alguien puede ayudarme con esto?

Respuesta #1

Se solucionó el problema. Básicamente, NextPageContext tiene los siguientes campos definidos en su interfaz:

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
}

Así que simplemente extendí la interfaz en mi _app.tsx. Algo así:

import {Store} from "redux";

export interface MyPageContext extends NextPageContext {
  store: Store;
  isServer: boolean;
}

Y ahora, siempre que tengo que usar getInitialProps en cualquier componente funcional, lo llamo así:

HelpDesk.getInitialProps = async (props: MyPageContext) => {
  const { query, store } = props;
  store.dispatch(getCategory());
  return { query };
};

Tomé inspiración de aquí

Respuesta #2

Haz esto para ver qué está pasando:

SupportHome.getInitialProps = async (something) => {
  console.log(something)
  //store.dispatch(getCategory());
  //return {
   // isServer,
  //  store
  //};
};

Si esto es lo que ves, entonces parece que las propiedades que deseas están en la subclave 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 }

Probablemente estás pasando el objeto incorrecto a esta función, por lo que el error está aguas arriba.

SupportHome.getInitialProps = async ({props}) => {
  console.log(props)
  const { store, isServer, store } = props
  store.dispatch(getCategory());
  return {
    isServer
    store
  };
};

Artículos relacionados