在 react 中,不能在组件外部或条件逻辑中调用 hook,因此无法将 `usefirebaseauth()` 等 hook 的返回函数(如 `signinwithapple`)直接写入全局常量数组。正确做法是将数据结构移入组件内或封装为自定义 hook,在符合 hook 规则的前提下动态构建映射。
React 的 Hook 规则(尤其是“只能在顶层调用 Hook”)意味着:所有 Hook 调用必须发生在函数组件体内部或自定义 Hook 内部,且不能出现在循环、条件或嵌套函数中。你最初尝试将 signInWithApple 直接赋值给全局 socialAuthMethodsMap 数组,违反了这一规则——因为此时 useFirebaseAuth() 尚未执行,signInWithApple 甚至不存在。
最直观、推荐的解法是将 socialAuthMethodsMap 移入组件作用域,确保 Hook 调用时机合法:
import { FunctionComponent, MouseEventHandler } from 'react';
import { IconProps } from 'react-feather';
import { SocialAuthButton } from './SocialAuthButton';
import { useFirebaseAuth } from './hooks/useFirebaseAuth';
type TSocialAuthMethodData = {
code: string;
logo?: string | FunctionComponent;
onClick: MouseEve
ntHandler;
};
const MyAuthPage = () => {
const { signInWithApple } = useFirebaseAuth();
const socialAuthMethodsMap: TSocialAuthMethodData[] = [
{
code: 'apple',
logo: '/assets/icons/social/apple.svg',
onClick: signInWithApple, // ✅ 合法:signInWithApple 已由 Hook 提供
},
{
code: 'google',
logo: '/assets/icons/social/google.svg',
onClick: () => console.log('Google login stub'),
},
{
code: 'github',
logo: '/assets/icons/social/github.svg',
onClick: () => console.log('GitHub login stub'),
},
];
return (
{socialAuthMethodsMap.map((method) => (
))}
);
};
export default MyAuthPage; 若多个组件需共享该认证方法配置,建议提取为 useSocialAuthData 自定义 Hook:
// hooks/useSocialAuthData.ts
import { useFirebaseAuth } from './useFirebaseAuth';
import { TSocialAuthMethodData } from '../types';
export const useSocialAuthData = (): TSocialAuthMethodData[] => {
const { signInWithApple } = useFirebaseAuth();
return [
{
code: 'apple',
logo: '/assets/icons/social/apple.svg',
onClick: signInWithApple,
},
{
code: 'google',
logo: '/assets/icons/social/google.svg',
onClick: () => alert('Google auth not implemented yet'),
},
{
code: 'github',
logo: '/assets/icons/social/github.svg',
onClick: () => alert('GitHub auth not implemented yet'),
},
];
};然后在组件中使用:
const MyAuthPage = () => {
const socialAuthMethodsMap = useSocialAuthData(); // ✅ Hook 调用合规
return (
{socialAuthMethodsMap.map((method) => (
))}
);
};通过将 Hook 调用与数据结构耦合在合法作用域内,你既能保持代码清晰可维护,又能完全遵守 React 的设计约束。这是现代 React 应用中管理“带副作用的静态配置”的标准范式。