在设置状态时将 React tinymce 与 react-hook-form 无限循环一起使用

Using React tinymce with react-hook-form infinite loop while setting the state

我正在尝试使用 react-hook-form 附带的 setValue 函数,当用户输入到 react tinymce 编辑器时,它会存储编辑器中输入的 html 数据: https://react-hook-form.com/api/useform/setvalue/.

它在使用 onClick 按钮时工作正常,当我单击按钮时,从 tinymce 编辑器键入的 html 数据通过使用 htmlContent 的 setValue 函数存储。

然而,当我尝试将 onEditorChange 或 onChange 函数与 setValue 一起使用时,react tinymce 编辑器不允许我输入它并且应用程序崩溃,我遇到了大约 5000 个控制台错误,这些错误在几秒钟内不断增加与组件无关,它一直以非常快的速度从另一个组件复制有关重复键的错误。

当尝试在提供的 onEditorChange 中使用 setValue 或使用 onChange 函数时,它似乎在执行无限循环并崩溃,但在使用按钮的相同逻辑 onClick 时工作正常。

import React, { useState } from 'react'
import { Editor } from '@tinymce/tinymce-react'
import { useFormContext } from 'react-hook-form'
import { HtmlEditorWrapper } from './HtmlEditor.styles'

type HtmlEditorProps = {
    name: string
}

export const HtmlEditorComponent = ({ name }: HtmlEditorProps): JSX.Element => {
    const [htmlContent, setHtmlContent] = useState('')
    const { setValue } = useFormContext()

    return (
        <>
            <HtmlEditorWrapper>
                <Editor
                    value={htmlContent}
                    apiKey={process.env.REACT_APP_TINYMCE_KEY}
                    onEditorChange={(content: string) => {
                        setHtmlContent(content)
                        // setValue(name, content)
                    }}
                    // onChange={() => setValue(name, htmlContent)}}
                    init={{
                        height: 200,
                        menubar: false,
                        plugins: [
                            'advlist autolink lists link image charmap print preview anchor',
                            'searchreplace visualblocks code fullscreen',
                            'insertdatetime media table paste code help wordcount',
                        ],
                        toolbar:
                            'undo redo | formatselect | ' +
                            'bold italic backcolor | alignleft aligncenter ' +
                            'alignright alignjustify | bullist numlist outdent indent | ' +
                            'removeformat | help',
                        content_style:
                            'body { font-family:Helvetica,Arial,sans-serif; font-size:14px, }',
                    }}
                />

                <button onClick={() => setValue(name, htmlContent)}>
                    Save desc
                </button>
                {htmlContent}
            </HtmlEditorWrapper>
        </>
    )
}

这是一个带有演示密钥的工作示例:https://codesandbox.io/s/stupefied-sutherland-09eh2

有多种方法可以实现您想要的效果。其中之一是使用 ControlleruseController.