injectIntl ​​вызывает ошибку после добавления gatsby-plugin-layout

Чтобы перевести свой сайт, я ввожу intl вот так в моем файле layout.js:

import React from "react";
import { injectIntl } from "gatsby-plugin-intl";

const Layout = ({intl}) => (
    {intl.formatMessage({id: "history_text"})}
);

export default injectIntl(Layout)

Но после того, как я добавил gatsby-plugin-layoutв свой проект (на основе этого примера) я получаю эту ошибку:
Error: [React Intl] Could not find required `intl` object. <IntlProvider> needs to exist in the component ancestry.

Как мне избавиться от этой ошибки, сохранив переводы?

Это соответствующая часть конфигурации gatsby:

{
    resolve: `gatsby-plugin-intl`,
    options: {
        path: `${__dirname}/src/locale`,
        languages: [`en`, `de`],
        defaultLanguage: `de`,
        redirect: false,
    },
},
{
    resolve: `gatsby-plugin-layout`,
    options: {
        component: require.resolve(`./src/components/layout.js`),
    },
},

1 ответ

Решение

gatsby-plugin-layout а также gatsby-plugin-intl оба используют wrapPageElement API для создания оболочки.

Теперь плагины в gatsby выполняются сверху вниз, поэтому вам нужно определить gatsby-plugin-layout перед gatsby-plugin-intl таким образом IntlProvider поставщик, используемый gatsby-plugin-intl, обертывает компонент Layout и может использовать injectIntl ​​HOC

{
    resolve: `gatsby-plugin-layout`,
    options: {
        component: require.resolve(`./src/components/layout.js`),
    },
},
{
    resolve: `gatsby-plugin-intl`,
    options: {
        path: `${__dirname}/src/locale`,
        languages: [`en`, `de`],
        defaultLanguage: `de`,
        redirect: false,
    },
},
Другие вопросы по тегам