kin*_*lex 5 reactjs react-hooks react-18
我正在开发一个组件,我从 URL 读取查询参数并在 useEffect 中发布请求,由于严格模式,这会执行两次。该请求是非幂等的,处理这种情况的最佳方法是什么?
我正在考虑维护一个包含请求是否已执行的引用,如果请求已执行则不执行该请求。
文档建议使用清理功能。清理函数不是阻止它触发两次,而是恢复第一次执行的效果,因此看起来效果好像只运行了一次。
例如,
useEffect( () => {
const dialog = dialogRef.current;
dialog.showModal();
// This will run after the first execution and close the modal that was just opened.
// Then the second execution will re-open it, and it will remain open.
return () => dialog.close();
}, [] );
Run Code Online (Sandbox Code Playgroud)