QuillJS selection-change 出于某种原因缓存结果

QuillJS selection-change caches results for some reason

我有:

    useEffect(() => {
        if (quill) {
            quill.clipboard.dangerouslyPasteHTML(documentContent);
            quill.on('text-change', () => {
                setDocumentContent(quill.root.innerHTML);
            });

            quill.on('selection-change', (range, oldRange, source) => {
                console.log(documentState?.predictionStatus, range, oldRange, source);
            })

        }
    }, [quill]);

documentState.predictionStatus 保持其原始值。我想也许是因为该值以某种方式被缓存了?

有什么办法解决吗?

谢谢!

你的代码是这样的吗?

    const [documentState, setDocumentState] = useState();
    useEffect(() => {
        if (quill) {
            quill.clipboard.dangerouslyPasteHTML(documentContent);
            quill.on('text-change', () => {
                setDocumentContent(quill.root.innerHTML);
            });

            quill.on('selection-change', (range, oldRange, source) => {
                console.log(documentState?.predictionStatus, range, oldRange, source);
            })

        }
    }, [quill]);

您正试图在 quill.on 的处理函数中访问 documentState?.predictionStatus 这可能会导致错误,因为您传递给 quill.on 的函数只记住 [= 的原始值15=](因为closure

要解决此问题,请 useRef 代替 documentState

    const documentRef = useRef();

    useEffect(() => {
        if (quill) {
            quill.clipboard.dangerouslyPasteHTML(documentContent);
            quill.on('text-change', () => {
                setDocumentContent(quill.root.innerHTML);
            });

            quill.on('selection-change', (range, oldRange, source) => {
                console.log(documentRef.current?.predictionStatus, range, oldRange, source);
            })

        }
    }, [quill]);

/// somewhere in you code update documentRef
documentRef.current = newValue