即使看到可能已解决问题,我仍然看到上述反应16.13.0警告。我确实经历了这个github问题https://github.com/facebook/react/issues/18147,似乎我已经在子组件内的useEffect挂钩内调用了setState回调。这是伪代码。
function Parent = () => {
const [enablePrint, updateEnablePrint] = useState(false);
function handlePrint() {
updateEnablePrint(true);
}
useEffect(() => {
function handlePrintViaKeyboard(e) {
if (e.key === 'p' && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
e.stopPropagation();
handlePrint();
}
}
window.addEventListener('keydown', handlePrintViaKeyboard, false);
return () => {
window.removeEventListener('keydown', handlePrintViaKeyboard);
};
}, []);
function afterPrint() {
updateEnablePrint(false);
}
return (
<ChildComponent <!-- This is the line where I get the warning -->
renderPrintComponent={props => <PrintComponent {...props} />}
enablePrint={enablePrint}
onAfterPrint={afterPrint}
>
/* some JSX */
</ChildComponent>
)
}
function ChildComponent = ({
children,
enablePrint,
onAfterPrint,
renderPrintComponent
}) => {
useEffect(() => {
function handleAfterPrint() {
if (onAfterPrint) onAfterPrint();
}
printListener.addAfterPrintListener(handleAfterPrint);
return () => {
printListener.removeAfterPrintListener(handleAfterPrint);
};
}, [onAfterPrint, printListener]);
return (
<div>
{children}
</div>
);
}
我什至尝试将ChildComponent的useEffect代码移至Parent,但仍然看到该警告。我不确定是什么导致该警告弹出。如您所见,afterPrint
方法在ChildComponent内部的useEffect挂钩中被调用。任何帮助表示赞赏。谢谢!