next.js 参考错误:使用ReactQuill时未定义文档

iibxawm4  于 2023-06-05  发布在  React
关注(0)|答案(1)|浏览(364)

我开始使用next.js和ReactQuill。但是当我运行yarn build时,这是我得到的:

info Creating an optimized production build
- info Compiled successfully
- info Linting and checking validity of types
- info Collecting page data ..ReferenceError: document is not defined
    at Object.<anonymous> (C:\Users\joao\Desktop\liceu\node_modules\quill\dist\quill.js:7661:12)
    at __webpack_require__ (C:\Users\joao\Desktop\liceu\node_modules\quill\dist\quill.js:36:30)
    at Object.<anonymous> (C:\Users\joao\Desktop\liceu\node_modules\quill\dist\quill.js:1030:1)
    at __webpack_require__ (C:\Users\joao\Desktop\liceu\node_modules\quill\dist\quill.js:36:30)
    at Object.<anonymous> (C:\Users\joao\Desktop\liceu\node_modules\quill\dist\quill.js:5655:14)
    at __webpack_require__ (C:\Users\joao\Desktop\liceu\node_modules\quill\dist\quill.js:36:30)
    at Object.<anonymous> (C:\Users\joao\Desktop\liceu\node_modules\quill\dist\quill.js:10045:13)
    at __webpack_require__ (C:\Users\joao\Desktop\liceu\node_modules\quill\dist\quill.js:36:30)
    at Object.<anonymous> (C:\Users\joao\Desktop\liceu\node_modules\quill\dist\quill.js:11557:18)
    at __webpack_require__ (C:\Users\joao\Desktop\liceu\node_modules\quill\dist\quill.js:36:30)

> Build error occurred
Error: Failed to collect page data for /Articles
    at C:\Users\joao\Desktop\liceu\node_modules\next\dist\build\utils.js:1152:15
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  type: 'Error'
}
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

我该怎么用?我安装了软件包,在pages文件夹下创建文件。文件如下所示:

import ReactQuill from 'react-quill';
import React, { useState, useEffect  } from 'react';

export default function Articles() {

    const [content, setContent] = useState<ReactQuill.Value>('');

    const handleChange = (value: ReactQuill.Value) => {
      setContent(value);
    };

    return (
      <ReactQuill theme="snow" />
    );
  }

我错过了什么?我该怎么弥补?

fcwjkofz

fcwjkofz1#

可以使用dynamic。请参见this example
看起来ReactQuill只能在浏览器上运行。您只能在客户端呈现此元素。我不知道你用的是什么版本的Next.js。您可以添加useIsMounted钩子:

function useIsMounted() {
  const isMounted = useRef(false)
  useEffect(() => {
    isMounted.current = true
    return () => {
      isMounted.current = false
    }
  }, [])

  return useCallback(() => isMounted.current, [])
}

Link to example
然后你就像这样:

import ReactQuill from 'react-quill'
import React, { useState, useEffect } from 'react'

export default function Articles() {
  const [content, setContent] = useState<ReactQuill.Value>('')
  const isMounted = useIsMounted()

  const handleChange = (value: ReactQuill.Value) => {
    setContent(value)
  }

  return isMounted() ? <ReactQuill theme="snow" /> : null
}

相关问题