我想将这个组件demo/src/JSONEditorReact.js或React.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、模式依赖的useEffect中卸载组件useEffect是正确的吗?还是应该创建另一个带有空依赖数组的useEffect,以获得与类组件相同的行为?
发布于 2022-03-28 12:01:25
只要销毁和重建JSONEditor不需要明显的时间或引起用户明显的视觉抽搐,您所做的一切都是好的。当组件被卸载时,编辑器将被清除。
但是,由于它似乎允许您更改现有实例(基于API)上的模式和JSON,所以我认为我应该这样做,而不是在这些更改时完全销毁并重新构建它:
const Editor = ({json, mode, onChange}) => {
const elRef = useRef(null);
const edRef = useRef(null);
useEffect(() => {
// On mount
const options = {
onChangeText: onChange,
onChangeJson: onChange,
};
const jsonEditor = edRef.current = new JSONEditor(elRef.current, options);
if (json) { //
jsonEditor.set(json); // I don't think you actually need these here,
} // I *think* `useEffect` callbacks are run in
if (mode) { // order so the below will do it. But...
jsonEditor.setMode(mode); //
} //
return () => {
// No `if`, you *know* it exists
jsonEditor.destroy();
edRef.current = null;
}
}, []);
useEffect(() => {
const jsonEditor = edRef.current;
if (!jsonEditor) { // I don't think this can happen
return;
}
if (json) {
jsonEditor.set(json);
}
if (mode) {
jsonEditor.setMode(mode);
}
}, [json, mode]);
return (
<div
className={styles.jsoneditor_react_container}
ref={elRef}
/>
);
};
export default Editor;但这更复杂,因此,如果您正在做的工作很好,并提供您想要的用户体验,您可能想不谈它。
https://stackoverflow.com/questions/71646942
复制相似问题