[英]Invalid hook call error when trying to set state
I have a scenario where I am forced to call a trigger method to show a modal from two different places, one using a hotkey combination and another by clicking on a toolbar button.我有一个场景,我被迫调用一个触发方法来显示来自两个不同位置的模式,一个使用热键组合,另一个通过单击工具栏按钮。 In order to do so I have the following code, where I call the
triggerCustomLinkModal
to set the state but then I am hit with the Invalid Hook call error
.为了做到这一点,我有以下代码,我在其中调用
triggerCustomLinkModal
来设置状态,但随后我遇到了Invalid Hook call error
。
import { useState, useCallback, useEffect } from "react"
import { Dialog } from "@blueprintjs/core"
const useLocalState = () => {
const [isShown, setIsShown] = useState(false)
const setState = useCallback((state) => {
setIsShown(state)
})
const getState = useCallback(() => {
return isShown
})
return {
setState,
getState
}
}
export const CustomLinkModalUI = () => {
const { getState } = useLocalState()
return (
<>
<Dialog isOpen={getState()} />
</>
)
}
export const triggerCustomLinkModal = () => {
const { setState } = useLocalState()
setState()
}
Expanding from Chris answer in the comments ( You can't use hooks outside React components . -> so you can't call useLocalState()
inside triggerCustomLinkModal
since triggerCustomLinkModal
is not a React component ):从评论中的克里斯回答扩展(你不能在React 组件之外使用钩子。->所以你不能在
triggerCustomLinkModal
中调用useLocalState()
,因为triggerCustomLinkModal
不是 React 组件):
You don't really need the useCallback hook or even the functions itself.你真的不需要 useCallback 钩子,甚至函数本身。 Aaccording to react docs :
根据反应文档:
Note
笔记
React guarantees that setState function identity is stable and won't change on re-renders.
React 保证 setState 函数标识是稳定的,并且不会在重新渲染时改变。 This is why it's safe to omit from the useEffect or useCallback dependency list.
这就是为什么从 useEffect 或 useCallback 依赖列表中省略是安全的。
This also means that using useCallback
hook to set a state it doesn't really make sense (because useCallback role is just to return a memoized callback
)这也意味着使用
useCallback
钩子设置状态并没有真正意义(因为 useCallback 角色只是返回a memoized callback
)
What you basically need is a state set up in the closest parrent component and pass the setIsShown
as a prop as well as the isShown
function.您基本上需要的是在最近的父组件中设置一个状态,并将
setIsShown
作为道具以及isShown
函数传递。
Your current implementation, even if it weren't for the error, it wouldn't refer to the same state since on each useLocalState()
you are initializing a fresh new state (so you are not pointing to the same state in CustomLinkModalUI
and triggerCustomLinkModal
)您当前的实现,即使不是因为错误,它也不会引用相同的状态,因为在每个
useLocalState()
上,您正在初始化一个新的状态(因此您在CustomLinkModalUI
和triggerCustomLinkModal
中没有指向相同的状态)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.