Gatsby渲染不正确

时间:2020-05-06 12:20:32

标签: gatsby

我花了10多个小时才终于复制。


import * as React from 'react'
import * as ReactDomServer from 'react-dom/server'
import * as ReactDom from 'react-dom'
import * as RehypeReact from 'rehype-react'
import * as unified from 'unified'

const Youtube = props => {
  return <p data-test="Youtube">test</p>
}

const P = props => {
  return <p data-test="ppp">{props.children}</p>
}

const options = {
  createElement: React.createElement,
  components: {
    youtube: Youtube,
    p: P,
  },
}

var processor = unified().use(RehypeReact, options)

export const MarkdownRenderer: React.FC<{}> = props => {
  const ast = {
    type: 'root',
    children: [
      {
        type: 'element',
        tagName: 'p',
        properties: {},
        children: [
          {
            type: 'element',
            tagName: 'youtube',
            children: [],
          },
        ],
      },
      {
        type: 'text',
        value: '\n',
      },
      {
        type: 'element',
        tagName: 'p',
        properties: {},
        children: [
          {
            type: 'text',
            value: 'xxxx',
          },
        ],
      },
      {
        type: 'element',
        tagName: 'p',
        properties: {},
        children: [
          {
            type: 'text',
            value: 'yyy',
          },
        ],
      },
    ],
    data: {
      quirksMode: false,
    },
  }

  const output = processor.stringify(ast)
  console.log(`>>>`, ReactDomServer.renderToString(output))
  // Outputs:
  // <div data-reactroot="">
  //   <p data-test="ppp"><p data-test="Youtube">test</p></p>
  //   <p data-test="ppp">xxxx</p>
  //   <p data-test="ppp">yyy</p>
  // </div>

  // But the dom in the browser is
  // <div>
  //   <p data-test="ppp"><p data-test="Youtube">test</p></p>
  //   <p data-test="Youtube">xxxx</p>
  //   <p>yyy</p>
  // </div>
  return output
}

setTimeout(() => {
  // here renders correctly
  // <div>
  //   <p data-test="ppp"><p data-test="Youtube">test</p></p>
  //   <p data-test="ppp">xxxx</p>
  //   <p data-test="ppp">yyy</p>
  // </div>
  ReactDom.render(<MarkdownRenderer />, document.body)
}, 5000)

来自服务器的代码很好,只是第一次渲染就搞砸了。也可以更改页面然后再返回。

如果您查看我粘贴的代码的内部(将示例放在此处),请阅读代码内部的注释,比我在代码块外部键入内容更容易理解

0 个答案:

没有答案