首页 > 解决方案 > useEffect trace origin for change

问题描述

我有一个组件在多个地方更新本地状态。

我也有一个useEffect关于状态的钩子。

我想知道哪个更改导致调用 useEffect 函数。有没有办法从事件起源的钩子回溯?

这里的痕迹没有清楚地说明事件的起源

trace log
   in App (at src/​index.js:9)
r @ backend.js:8032
eval @ App.js? [sm]:11
commitHookEffectListMount @ react-dom.development.js:19731
commitPassiveHookEffects @ react-dom.development.js:19769
callCallback @ react-dom.development.js:188
invokeGuardedCallbackDev @ react-dom.development.js:237
invokeGuardedCallback @ react-dom.development.js:292
flushPassiveEffectsImpl @ react-dom.development.js:22853
unstable_runWithPriority @ scheduler.development.js:653
runWithPriority$1 @ react-dom.development.js:11039
flushPassiveEffects @ react-dom.development.js:22820
eval @ react-dom.development.js:22699
workLoop @ scheduler.development.js:597
flushWork @ scheduler.development.js:552
performWorkUntilDeadline @ scheduler.development.js:164

我尝试在 useEffect 中添加 console.log 和控制台跟踪,但它没有显示哪个 setState 调用它。

这是示例代码

const [state, setState] = React.useState(0);

React.useEffect(() => {
   console.log('Here I want to know if #1 or #2 caused this event for debugging purposes');
}, [state]);


const onClick1 = () => {
   setState(1); //#1 first call of setState
}

const onClick2 = () => {
   setState(2); //#2 second call of setState
}

这只是一个示例片段,但实时场景中的问题要复杂得多,因为我至少有 50 个我正在调用的地方,setState我希望在 useEffect 中进行调试以确定哪些地方setState实际上弄乱了我的数据。

这是一个复制行为的小提琴:https ://codesandbox.io/s/hardcore-bush-m6jdd?file=/src/App.js

标签: reactjs

解决方案


想法:创建一个包装器setState并调试/记录这样的包装器。确保setState永远不会从任何其他地方调用。

我认为 React 在设计上将状态的设置和可能由此产生的动作解耦了。恕我直言,这样做是为了强制应用程序的正确设计(一种发布-订阅机制),但它很难解决您面临的问题(例如,检查调用堆栈中的调用堆栈,useEffect您将看不到setState导致重新-使成为)。


推荐阅读