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

React Navigation向根屏幕传对象时出现undefined问题求助

React Navigation传递数据到组件出现undefined的解决方法

问题原因

你在AccountStack.Screen中直接添加自定义属性isSignedIn={{isSignedIn}}的方式无效,React Navigation的Screen组件只会识别其预设的props(如name、component、options、initialParams等),自定义属性不会被传递给指定的组件,这就导致Account组件中无法获取到该值,显示为undefined。

解决方法

提供两种可行的实现方案:

方案1:使用initialParams传递参数

修改AccountStackScreen中的AccountStack.Screen代码,将参数放入initialParams:

return (
    <AccountStack.Navigator screenOptions={{
        headerStyle: {
          backgroundColor: '#FEE6E9',
        },
        headerTintColor: '#fff',
        headerTitleStyle: {
          fontWeight: 'bold',
          color: '#444444',
        },
        headerBackTitleVisible: false,
        headerShadowVisible: false,
    }}>
        <AccountStack.Screen 
            name='Account'
            component={Account}
            options={{title: 'My Account'}}
            // 将参数放入initialParams
            initialParams={{ isSignedIn: isSignedIn }}
        />
    </AccountStack.Navigator>
)   

然后在Account组件中从route.params里读取参数:

export default function Account({ route }) {
    // 从route.params中解构获取isSignedIn
    const { isSignedIn } = route.params;
    console.log({ isSignedIn }) // 现在能正确获取到值
}

方案2:通过children函数直接传参

这种方式和你之前在Tab.Screen中使用的写法一致,直接在Screen的children里渲染Account组件并传递props:

return (
    <AccountStack.Navigator screenOptions={{
        headerStyle: {
          backgroundColor: '#FEE6E9',
        },
        headerTintColor: '#fff',
        headerTitleStyle: {
          fontWeight: 'bold',
          color: '#444444',
        },
        headerBackTitleVisible: false,
        headerShadowVisible: false,
    }}>
        <AccountStack.Screen 
            name='Account'
            options={{title: 'My Account'}}
        >
            {/* 通过children直接渲染并传参 */}
            {() => <Account isSignedIn={isSignedIn} />}
        </AccountStack.Screen>
    </AccountStack.Navigator>
)   

此时Account组件无需修改,保持原来的写法即可正常获取值:

export default function Account({ isSignedIn }) {
    console.log({ isSignedIn }) // 正确获取到值
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 10:35:21