为什么在导出访问 useAtom 状态的简单单个函数时"React hook is called in a function"?



我有一个简单的函数,它需要从jotai设置一个状态。我希望这个函数有自己的独立文件或在某个地方清理,因为它将被重用。我是React新手,来自Angular。它是Angular服务中的一个函数。

如何在React中正确解决这个问题?

代码:

export const setMetamaskWallet = (): void => {
const [, setWeb3] = useAtom(web3Atom);
const [, setLoading] = useAtom(loadingAtom);
const [wallet, setWallet] = useAtom(walletAtom);
setWeb3(
new Web3(window.ethereum),
)
//Todo: Create check if metamask is in browser, otherwise throw error
const setAccount = async () => {
setLoading(true);
const accounts = await window.ethereum.request(
{
method: 'eth_requestAccounts'
},
);
setWallet(
accounts[0],
);
setLoading(false);
}
if (!wallet) {
setAccount();
}
}

Hooks只能在React功能组件或其他钩子中调用。在这里,您似乎在一个典型的函数中调用了它,因此出现了错误。您可以将此功能打包到自定义钩子中。然而,保持这个函数不变可能是最合适的,而不是在其中调用钩子,而是将相关数据作为参数传递给函数。

最新更新