Next.js Warning: A title element received an array with more than 1 element as children

2023-01-19 21:56:46nextjsframework

Next.js报错:

Warning: A title element received an array with more than 1 element as children.

参考链接:https://github.com/vercel/next.js/discussions/38256#discussioncomment-3070196

问题复现:

在添加seo信息时,出现了一个错误:

Warning: A title element received an array with more than 1 element as children.

const Home = () => {
    const world = "World";
    const article = {title: 'test'}

    return (
        <div>
            <Head>
                <title>{article.title}-网站详情</title>
            </Head>
        </div>
    );
};

解析器就会将上述代码解析为:

<title><!-- -->test<!-- -->-网站详情</title>

概念:

节点: textNode (文本,注释,所有html标签:"text", , ,

)

标签: element (body,div,span,a ...)

title标签中,只能有一个子节点,如果出现多个子节点,就会出现上面的错误提示。

这里的节点,包含文本节点,就拿上面代码来说:

title中出现了四个节点:comment, text, comment, text

解决方法:

只给title保留一个文本节点

const Home = () => {
    const world = "World";
    const article = {title: 'test'}
    const title = `${article.title}-网站详情`
    return (
        <div>
            <Head>
                <title>{title}</title>
            </Head>
        </div>
    );
};