错误:MyDocument.getInitialProps()”应解析为带有“ html”道具的对象,该道具带有有效的html字符串(在document.js中)

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

现在我正在用React + Node JS +下一台服务器+ 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;
```
reactjs
1个回答
0
投票

您缺少需要由getInitialProps返回的html道具。您可以像下面这样从Document的初始道具中获取:

static async getInitialProps(ctx) {
  const initialProps = await Document.getInitialProps(ctx)
  return { ...initialProps, helmet: Helmet.renderStatic() }
}
© www.soinside.com 2019 - 2024. All rights reserved.