错误:MyDocument.getInitialProps()" 应该解析为一个带有“html”属性的对象,该属性集带有一个有效的 html 字符串(在 document.js 中)

IT技术 reactjs
2021-05-24 02:31:18

现在我正在用 react + node js + next server + express 做一个小项目

并发生意外错误

不知道为什么_document.js 会出现错误。

如果你知道原因,谢谢你告诉我

错误:

Error: "MyDocument.getInitialProps()" should resolve to an object with a "html" prop set with a valid html string
    at Object.renderToHTML (C:\node_bird_44\front\node_modules\next\dist\next-server\server\render.js:338:15)
    at process._tickCallback (internal/process/next_tick.js:68:7)
GET / 500 11240.415 ms - 21
[ event ] disposing inactive page(s): /, /_error
import React from 'react';
import Document , {Main, NextScript } from 'next/document';
import Helmet from 'react-helmet';

class MyDocument extends Document {
    static getInitialProps(context) {
        return { helmet: Helmet.renderStatic()};
    }

    render() {

        const { htmlAttributes, bodyAttributes, ...helmet } = this.props.helmet;
        const htmlAttrs = htmlAttributes.toComponent();
        const bodyAttrs = bodyAtributues.toComponent();

        return(
            <html {...htmlAttrs}>
                <head>
                    {Object.values(helmet).map(el => el.toComponent())}
                </head>
                <body {...bodyAttrs}>
                    <Main />
                    <NextScript />
                </body>
            </html> 
        );
    }
}


export default MyDocument;
```
1个回答

您缺少html需要由 getInitialProps 返回props。您可以从 Document 初始props中获取它,如下所示:

static async getInitialProps(ctx) {
  const initialProps = await Document.getInitialProps(ctx)
  return { ...initialProps, helmet: Helmet.renderStatic() }
}