简体   繁体   English

如何在 React 中找到调用自定义 hook 的组件?

[英]How to find the component calling a custom hook in React?

I've a custom hook being called by multiple components, including other custom hooks.我有一个自定义挂钩被多个组件调用,包括其他自定义挂钩。 I added an useEffect in the custom hook to run on only initial render with console.trace() , to figure out the caller component.我在自定义挂钩中添加了一个 useEffect 以仅在使用console.trace()的初始渲染上运行,以找出调用者组件。

useEffect(() => {
  console.trace()
}, [])

But this logs the stack trace with invokePassiveCreate at the top.但这会在顶部记录带有invokePassiveCreate的堆栈跟踪。 I can't find the caller from the stack trace.我无法从堆栈跟踪中找到调用者。 Is there another way to figure it out?还有另一种方法可以解决吗?

堆栈跟踪

useEffect is invoked by React so here we did not get the caller of the custom hook or any component. useEffect 是由 React 调用的,所以这里我们没有得到自定义钩子或任何组件的调用者。 use console.trace() outside useEffect.在 useEffect 之外使用 console.trace()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在自定义反应挂钩中获取当前反应组件名称? - how to get current react component name inside custom react hook? 如何将 React 组件的自定义钩子与“map”一起使用 - How to use React component's custom hook with “map” 如何在同一个组件中使用自定义反应查询钩子两次? - How to use custom react query hook twice in the same component? 在自定义组件中调用 useState Hook 时反应本机 TextInput ReRenders - React Native TextInput ReRenders when calling useState Hook inside a custom component React 使用自定义钩子检测组件外的点击 - React detect click outside a component with custom hook 使用自定义钩子提供的数据测试 React 组件 - Testing React component with data provided by custom hook 如何将此 React 钩子组件转换为功能组件 - How to convert this React hook component into a functional component 自定义 React 组件(react-hook)不重新渲染 - Custom React component(react-hook) not re-rendering 如何将自定义下拉组件的值传递给 react-hook-form? - How to pass a value from a custom dropdown component to react-hook-form? 如何创建一个自定义钩子,它的工作方式类似于 React with Typescript 中类组件中的 setState - How to create a custom hook, that works like setState in a class component in React with Typescript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM