0

为了翻译我的网站,我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`),
    },
},
4

1 回答 1

1

gatsby-plugin-layout并且gatsby-plugin-intl都使用wrapPageElementAPI 来创建包装器。

现在 gatsby 中的插件是自上而下执行的,因此您需要在gatsby-plugin-layout之前定义,gatsby-plugin-intl以便IntlProvidergatsby-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,
    },
},
于 2020-05-02T18:34:44.057 回答