我有一个奇怪的案例,希望得到一些反馈。 想象一下我有一个名为
EditorWrapper
的组件。
在我下面写的三个
useEffect
中,第二个仅在我第一次渲染 EditorWrapper
组件时起作用,如果我卸载该组件并再次渲染它,它会停止工作(即编辑器不工作) t 接收值“Hi”) - 即使 console.log
正在被调用。即使我不卸载 EditorWrapper
并仅渲染它的多个实例,也会发生类似的行为。
对此有何可能解释?我已经没有选择了。
抱歉没有提供可重现的示例,我有一些网络限制,无法打开沙箱和类似网站,并且在我可以打开的网站上,由于某些原因我无法让编辑器工作。
// Other EditorWrapper component code...
// 1 Works when multiple instances of this component are created
// React.useEffect(() => {
// setTimeout(() => {
// editor.current?.setValue("Hi");
// });
// }, []);
// 2 Works only when component is rendered once
React.useEffect(() => {
Api.get("/doc/" + id, {})
.then((x) => {
console.log("Then called");
editor.current?.setValue("Hi");
})
}, []);
// 3 Works when multiple instances of this component are created
// React.useEffect(() => {
// editor.current?.setValue("Hi");
// }, []);
return (
<div>
<CKEditor ref={editor} />
</div>
);
首先,您没有发布足够的代码来重现问题。我们不知道您正在使用什么版本的
react
和 @ckeditor
,我们不知道您正在使用什么类型的编辑器(经典、内联或气球),我们也不知道您如何使用它。
但是,我认为正在发生的事情是这样的:
<CkEditor />
是一个重组件。初始化需要一段时间。为此,它公开了 state
属性,该属性可以是 'ready' | 'initializing' | 'destroyed'
类型。
第一次使用 API (
/doc/
) 时,请求所需的时间超过 <CkEditor />
需要初始化的时间,当您将其值设置为 'Hi'
时,它可以正常工作。
但是在同一组件的后续安装中,(
/doc/
) 的响应由浏览器缓存提供,这通常需要少于 20ms
,并且 <CkEditor />
需要更多时间才能退出 'initializing'
状态。因此,对 setValue
的调用没有任何效果。
要解决这个问题,你必须:
<CkEditor />
useEffect()
。大致如下:
const EditorWrapper = () => {
const [editorState, setEditorStae] = React.useState('')
React.useEffect(() => {
Api.get('/doc/' + id, {}).then((x) => {
console.log('Then called')
if (editorState === 'ready') {
editor.current?.setValue('Hi')
}
})
}, [])
React.useEffect(() => {
console.log('Editor state changed...')
if (editorState === 'ready') {
editor.current?.setValue('Hi')
}
}, [editorState])
return (
<div>
<CKEditor
ref={editor}
change:state={(eventInfo, name, value) => setEditorState(value)}
/>
</div>
)
}
如果上述方法不起作用,您确实应该考虑使用codesandbox.io或类似服务创建一个可运行最小可重现示例。