简体   繁体   English

如何在钩子内调用钩子? (或替代,因为这无法完成:D)

[英]How to call a hook inside a hook? (or alternative as this cant be done :D)

so I've created a custom hook that needs to be fired on page view所以我创建了一个需要在页面视图上触发的自定义钩子

so I thought I could just call this hook inside useEffect but it doesn't look like this is possible所以我想我可以在useEffect调用这个钩子,但看起来这是不可能的

so does anyone know how I can do this?有谁知道我该怎么做?

it will be triggering Google Analytics once I fire it so it has to be onload.一旦我启动它,它就会触发谷歌分析,所以它必须被加载。 is this possible?这可能吗?

ok here's an example好的,这是一个例子

export const usePageView = props => {
    const counter = useSelector(state => state) // useSelector coming from react redux
    console.log(counter, '===')
}

import { usePageView } from '../myhooks'

export const myComponent = () => {
   useEffect(() => {
      usePageView() // get error saying Error: Invalid hook call.
},[])

}

The Rules of Hooks state to only call hooks from the top level of a function.钩子规则规定只能从函数的顶层调用钩子。

Don't call Hooks inside loops, conditions, or nested functions.不要在循环、条件或嵌套函数中调用 Hook。 Instead, always use Hooks at the top level of your React function.相反,始终在 React 函数的顶层使用 Hook。 By following this rule, you ensure that Hooks are called in the same order each time a component renders.通过遵循此规则,您可以确保每次渲染组件时以相同的顺序调用 Hook。 That's what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls.这就是允许 React 在多个 useState 和 useEffect 调用之间正确保留 Hooks 状态的原因。

You can not compose a custom hook into a useEffect call because that is by definition an "nested function".您不能将自定义挂钩组合到useEffect调用中,因为根据定义,这是一个“嵌套函数”。 Instead, you should build your custom hooks to include all the hooks or useEffect calls they need to do inside the custom hook (but at the top level of the custom hook).相反,您应该构建您的自定义钩子以包含他们需要在自定义钩子执行的所有钩子或useEffect调用(但在自定义钩子的顶层)。

https://reactjs.org/docs/hooks-rules.html#only-call-hooks-at-the-top-level https://reactjs.org/docs/hooks-rules.html#only-call-hooks-at-the-top-level

It would be helpful to have more specific code of what exactly you are trying to do, because currently your question is too vague to give a more direct answer.这将是有帮助的正是你正在尝试做更具体的代码,因为目前你的问题太模糊,以提供更直接的答案。

You don't need here an useEffect .这里不需要useEffect

export const usePageView = props => {
    const counter = useSelector(state => state) // useSelector coming from react redux
    console.log(counter, '===')
}
import { usePageView } from '../myhooks'

export const myComponent = () => {
      usePageView();
}

This should work.这应该有效。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM