React 功能组件卸载
我想重写这个组件https://github。 com/josdejong/jsoneditor/blob/master/examples/react_advanced_demo/src/JSONEditorReact.js 到一个功能组件。 我做了这个:
const Editor = ({json, mode, onChange}) => {
const elRef = useRef(null);
useEffect(() => {
const options = {
onChangeText: onChange,
onChangeJson: onChange,
};
const jsonEditor = new JSONEditor(elRef.current, options);
if (jsonEditor) {
if (json) {
jsonEditor.set(json);
}
if (mode) {
jsonEditor.setMode(mode);
}
}
return () => {
if (jsonEditor) {
jsonEditor.destroy();
}
}
},[json,mode]);
return (
<div
className={styles.jsoneditor_react_container}
ref={elRef}
/>
)
}
export default Editor;
我的问题是:使用 [json, mode] 依赖项卸载 useEffect 中的组件 jsonEditor.destroy();
是否正确,或者我应该使用空依赖项数组创建另一个 useEffect 以获得相同的行为就像在类组件中一样?
I want to rewrite this component https://github.com/josdejong/jsoneditor/blob/master/examples/react_advanced_demo/src/JSONEditorReact.js
to a functional component.
I made this:
const Editor = ({json, mode, onChange}) => {
const elRef = useRef(null);
useEffect(() => {
const options = {
onChangeText: onChange,
onChangeJson: onChange,
};
const jsonEditor = new JSONEditor(elRef.current, options);
if (jsonEditor) {
if (json) {
jsonEditor.set(json);
}
if (mode) {
jsonEditor.setMode(mode);
}
}
return () => {
if (jsonEditor) {
jsonEditor.destroy();
}
}
},[json,mode]);
return (
<div
className={styles.jsoneditor_react_container}
ref={elRef}
/>
)
}
export default Editor;
My question is next: Is it correct to unmount the component jsonEditor.destroy();
inside that useEffect with [json, mode] dependancies or i should create another useEffect with empty dependancy array to get the same behaviour as in class component?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只要销毁和重建 JSONEditor 不会花费明显的时间或导致用户明显的视觉抽搐,您所做的就很好。卸载组件时,编辑器将被清理。
但是,因为它似乎允许您在现有实例上更改模式和 JSON(基于 API),我想我会这样做,而不是完全销毁它并在这些变化时重建它:
但这更复杂,所以如果你正在做的事情运作良好并提供您想要的用户体验,您可能不想管它。
What you're doing is fine provided that destroying and rebuilding the
JSONEditor
doesn't take discernible time or cause a visual twitch that's apparent to the user. The editor will be cleaned up when the component is unmounted.But, since it seems to allow you to change mode and JSON on an existing instance (based on the API), I think I'd do that rather than completely destroying it and rebuilding it when those change:
But that's more complicated, so if what you're doing works well and provides the user experience you want, you might want to leave it alone.