所以我刚刚遇到了这个问题并使用装饰器属性解决了它。
{
strategy: handleSentenceStrategy,
component: SentenceComponent,
props: {
setSentenceFocus,
},
},
而setSentenceFocus 只是创建编辑器的任何反应回调挂钩(或静态函数)。
主要问题是每当道具发生变化时,它都会重新渲染组件(这是正确的),因此如果您传入编辑器状态,您的性能(和视觉渲染)就会出现问题。
我通过略显老套的 useRef 方法解决了这个问题。
const editorStateRef = useRef<EditorState>(editorState)
editorStateRef.current = editorState
const updateSentenceFocus = useCallback((focusedSentence: string) => {
const editorState = editorStateRef.current
const newEditorState = doSomething()
setEditorState(newEditorState)
}, [])
这里的重点是回调本身永远不会改变,并且使用静态 ref 引用。这使它更加优化。
如果您在击键时执行操作,这可能(很可能会)导致渲染顺序方面的问题,但它适用于我的用例。如果您做的不仅仅是一个小调整,我建议您使用 blockRendererFn,它可以为您提供最大的灵活性(具有更多的复杂性权衡)。
反之亦然(尽管我不建议亲自更新装饰器中的 editorState)。
{
strategy: handleSentenceStrategy,
component: SentenceComponent,
props: {
getEditorState,
},
},
const getEditorState = useCallback((): EditorState => {
return editorStateRef.current
}, [])
希望这是有道理的!