简体   繁体   中英

Connecting NextJS, next-i18next, with-redux, with-redux-saga: "Error: If you have a getInitialProps method in your custom _app.js file..."

I'm trying to connect a functioning NextJS/React app that uses 'with-redux-saga' and 'with-redux' to 'next-i1iN' ( https://github.com/isaachinman/next-i18next ) -- but when my app boots I get the following error:

Error: If you have a getInitialProps method in your custom _app.js file, you must explicitly return pageProps. For more infor mation, see: https://github.com/zeit/next.js#custom-app

TypeError: Cannot read property 'namespacesRequired' of undefined at Function.getInitialProps (/Users/cerulean/Documents/Projects/PAW-React/node_modules/next-i18next/dist/hocs/app-with-translation.js:94:57) at process._tickCallback (internal/process/next_tick.js:68:7)

But I am returning page props in my _app.js .

// _app.js
 static async getInitialProps({ Component, ctx }) {

    const pageProps = {};
    let temp;

    if (Component.getInitialProps) {
      temp = await Component.getInitialProps({ ctx });
    }
    Object.assign(pageProps, temp);
    return { ...pageProps };
  }

Perhaps there is something wrong with how I am hooking together the various HOCs? In _app.js I have:

export default withRedux(createStore, { debug: false })(withReduxSaga({ async: true })(i18nInstance.appWithTranslation(MyApp)));

And in my index.js I have:

   // index.js
const mapStateToProps = (state) => ({ homeData: getHomePageData(state) });

export default connect(mapStateToProps)(withNamespaces('common')(Index));

Any insights much appreciated!

For anyone coming to this issue and wondering what @cerulean meant in his answer .

1) use require instead of import

NextJS doesn't transpile your modules if you use a custom server ( more info ). Therefore you cannot use import in your next-i18next configuration without going through a vale of tears.

// NextI18NextConfig.js

const NextI18Next = require('next-i18next/dist/commonjs')

module.exports = new NextI18Next({
  defaultLanguage: "en",
  otherLanguages: ["de"]
  // ... other options
});
// server.js

const nextI18next = require("./path/to/NextI18NextConfig");

// ... the rest of your server.js code

This is a mix&match from next-i18next example and documentation


2) keep pageProps as it is

You cannot play too much with getInitialProps returned value. If you need to add extra stuff you should be careful not replacing or manipulating pageProps . See below.

  static async getInitialProps({ Component, ctx }) {
    let pageProps = {}

    const extraStuff = doSomeExtraStuff()

    if (Component.getInitialProps) {
      pageProps = await Component.getInitialProps(ctx)
    }

    return { pageProps, extraStuff }
  }

More about it on this thread .

如果您正确配置了 redux sagas,这种方式对我有用:

export default withRedux(configureStore)(withReduxSaga(appWithTranslation(MyApp)));

Two things for those who encounter a similar situation.

1) When they say 'return pageProps', it means 'return pageProps', not '...pageProps'

2) I was using ES6 import statements in the file which set up the 'next-i18next' singleton. Needed to use 'require' and 'module.exports'

Now it works...

I still can't make it work, and the code looks ok. Has anyone any idea about this? It results in error

Cannot read property 'namespacesRequired' of undefined

// pages/_app.js

import App from 'next/app';
import React from 'react';
import { Provider } from 'react-redux';
import withRedux from 'next-redux-wrapper';
import withReduxSaga from 'next-redux-saga';
import { appWithTranslation } from '../i18n';

import createStore from '../lib/store';

class MyApp extends App {
  static async getInitialProps({ Component, ctx }) {
    let pageProps = {};

    if (Component.getInitialProps) {
      pageProps = await Component.getInitialProps({ ctx });
    }

    return { pageProps };
  }

  render() {
    const { Component, pageProps, store } = this.props;
    return (
      <Provider store={store}>
        <Component {...pageProps} />
      </Provider>
    );
  }
}

export default appWithTranslation(withRedux(createStore)(withReduxSaga(MyApp)));



// i18n.js
const NextI18Next = require('next-i18next/dist/commonjs').default;

module.exports = new NextI18Next({
  otherLanguages: ['en', 'pl'],
  strictMode: false
});



// server.js
const express = require('express');
const next = require('next');
const nextI18NextMiddleware = require('next-i18next/middleware').default;
const nextI18next = require('./i18n');

const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const routes = require('./routes');

const handle = routes.getRequestHandler(app);
app.prepare().then(() => {
  const server = express();
  server.use(nextI18NextMiddleware(nextI18next));
  server.get('*', (req, res) => handle(req, res));
  server.listen(port, err => {
    if (err) throw err;
    console.log(`> Ready on http://localhost:${port}`);
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM