Sha*_*oon 5 javascript typescript quill
我有:
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]);
Run Code Online (Sandbox Code Playgroud)
但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]);
Run Code Online (Sandbox Code Playgroud)
您正在尝试访问 documentState?.predictionStatus其处理函数内部,quill.on该函数可能会导致错误,因为您传递给的函数quill.on仅记住原始值documentState(因为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
Run Code Online (Sandbox Code Playgroud)