注入gatsby-plugin-layout后,注入Intl导致错误。

问题描述 投票:0回答:1

为了翻译我的网站,我在我的网站上注入了以下内容 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`),
    },
},
gatsby gatsby-plugin-intl
1个回答
1
投票

gatsby-plugin-layout &gt; ( {intl.... gatsby-plugin-intl 都利用 wrapPageElement API来创建一个包装器。

现在,gatsby中的插件是自上而下执行的,因此你需要定义 gatsby-plugin-layout 之前 gatsby-plugin-intl 以致于 IntlProvider gatsby-plugin-intl使用的provider包装了Layout组件,并且它能够使用injectionIntl 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,
    },
},
© www.soinside.com 2019 - 2024. All rights reserved.