reactjs - 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
解决方案
想法:创建一个包装器setState
并调试/记录这样的包装器。确保setState
永远不会从任何其他地方调用。
我认为 React 在设计上将状态的设置和可能由此产生的动作解耦了。恕我直言,这样做是为了强制应用程序的正确设计(一种发布-订阅机制),但它很难解决您面临的问题(例如,检查调用堆栈中的调用堆栈,useEffect
您将看不到setState
导致重新-使成为)。
推荐阅读
- reactjs - 如何创建在状态更改时运行的触发函数?
- visual-studio-code - 如何访问 VSCode 拉取请求检查的 Azure 管道构建信息?
- javascript - 如何添加孩子
- 元素到
- 不删除当前的孩子
- 元素到
- c - 从 gcc 中的另一个目录链接目标文件(使用命令提示符)
- python-3.x - 使用转置和展平的数据框转换
- javascript - ReactNative:如何使用 useState 和 useMemo
- javascript - 每个索引中的分页
- c# - 在 OnPost() 之前调用 BindProperty 对象上的只读属性
- python - 微软 OAuth2 SMTP
- vb.net - 将 DataGridView 数据保存到 Access 数据库