使用常规的 React 可能会有这样的事情:
class NoteEditor extends React.PureComponent {
constructor() {
super();
this.state = {
noteId: 123,
};
}
componentWillUnmount() {
logger('This note has been closed: ' + this.state.noteId);
}
// ... more code to load and save note
}
Run Code Online (Sandbox Code Playgroud)
在 React Hooks 中,可以这样写:
function NoteEditor {
const [noteId, setNoteId] = useState(123);
useEffect(() => {
return () => {
logger('This note has been closed: ' + noteId); // bug!!
}
}, [])
return '...';
}
Run Code Online (Sandbox Code Playgroud)
返回的内容useEffect只会在组件卸载之前执行一次,但是状态(如上面的代码中所示)将是陈旧的。
一种解决方案是noteId作为依赖项传递,但是效果将在每次渲染上运行,而不仅仅是一次。或者使用引用,但这很难维护。 …