You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Expo加载字体时遭遇React Hook调用顺序错误问题求助

解决Expo加载字体时的Hook调用顺序错误

错误原因

React强制要求组件每次渲染时,Hook的调用顺序和数量必须完全一致。你的代码存在两个问题:

  • 遗漏了View和Text组件的导入,导致渲染报错,间接干扰Hook的正常执行逻辑
  • 字体未加载时直接返回null,结合useFonts内部的状态变化,导致两次渲染的Hook调用数量/顺序不一致

修复方案

方案1:补全导入并替换null返回为加载组件

修改WelcomePage.js代码:

import {Link, useRouter} from "expo-router";
import {View, Text} from "react-native"; // 补全必须的组件导入
import {windowForm} from "../Design/WindowForm";
import {Button} from "react-native-paper";
import Styles from "../Design/styles";
import Constants from "expo-constants";
import {Inter_900Black, useFonts} from "@expo-google-fonts/inter";

const WelcomePage = () => {
    // 所有Hook必须放在组件最顶部,顺序固定
    const router = useRouter()
    const [fontsLoaded] = useFonts({
        Inter_900Black,
    });

    // 用加载占位组件替代返回null,保持组件渲染结构一致
    if (!fontsLoaded) {
        return (
            <View style={{flex:1, justifyContent:'center', alignItems:'center'}}>
                <Text>加载中...</Text>
            </View>
        );
    }

    return(
        <View style={{width: windowForm().at(0), height:windowForm().at(1)}}>
            <Text style={{fontFamily:'Inter_900Black'}}>
                Hey
            </Text>
        </View>
    )
}
export default WelcomePage

方案2:根组件统一处理字体加载

将字体加载逻辑移到根组件(Index.js),确保字体在应用启动时完成加载,子组件无需处理加载状态:

修改Index.js:

import WelcomePage from "./Authentication/WelcomePage";
import {Inter_900Black, useFonts} from "@expo-google-fonts/inter";
import {View, Text} from "react-native";

export default function Page() {
    const [fontsLoaded] = useFonts({
        Inter_900Black,
    });

    if (!fontsLoaded) {
        return (
            <View style={{flex:1, justifyContent:'center', alignItems:'center'}}>
                <Text>加载中...</Text>
            </View>
        );
    }

    return (
        <WelcomePage/>
    );
}

修改WelcomePage.js:

import {Link, useRouter} from "expo-router";
import {View, Text} from "react-native";
import {windowForm} from "../Design/WindowForm";
import {Button} from "react-native-paper";
import Styles from "../Design/styles";
import Constants from "expo-constants";

const WelcomePage = () => {
    const router = useRouter()

    return(
        <View style={{width: windowForm().at(0), height:windowForm().at(1)}}>
            <Text style={{fontFamily:'Inter_900Black'}}>
                Hey
            </Text>
        </View>
    )
}
export default WelcomePage

内容的提问来源于stack exchange,提问作者Lytrix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 19:15:56