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

React Native+Redux+Navigation 6受保护路由启动Store未识别报错求助

问题分析与解决方案

错误原因

你遇到的报错是:Error: could not find react-redux context value; please ensure the component is wrapped in a <Provider>,根源是你在App组件的顶层直接调用了useSelector,但此时Redux Provider还未渲染,组件无法获取到Redux Store的上下文。

修复步骤

  1. 抽离路由逻辑到Provider内部组件
    将包含useSelector和路由判断的代码单独拆成一个组件,让它处于Provider的包裹范围内,这样就能正常访问Redux Store上下文。

  2. 修改后的完整代码

// 单独抽离路由导航组件
const AppNavigator = () => {
  const Stack = createNativeStackNavigator();
  const { isLoggedIn } = useSelector((state) => state.auth);

  return (
    <NavigationContainer>
      <Stack.Navigator
        initialRouteName='Login'
        headerMode='screen'
        options={{
          headerTitle: (props) => (
            <View style={styles.containerStyle}>
              <DropDown
                label={'Gender'}
                mode={'outlined'}
                value={category}
                setValue={setCategory}
                list={menuList}
                visible={showDropDown}
                showDropDown={() => setShowDropDown(true)}
                onDismiss={() => setShowDropDown(false)}
                inputProps={{
                  right: <TextInput.Icon name={'menu-down'} />,
                }}
              />
            </View>
          ),
          headerStyle: {
            backgroundColor: '#f4511e',
          },
          headerTintColor: '#fff',
          headerTitleStyle: {
            fontWeight: 'bold',
          },
        }}
      >
        {isLoggedIn ? (
          <>
            <Stack.Screen name='Home' component={Home} />
            <Stack.Screen name='comments' component={CommentsFeed} />
          </>
        ) : (
          <>
            <Stack.Screen name='Login' component={Login} />
            <Stack.Screen name='Register' component={Register} />
          </>
        )}
      </Stack.Navigator>
    </NavigationContainer>
  );
};

// 主App组件
export default function App() {
  return (
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
        <StatusBar animated={true} barStyle='light-content' />
        <PaperProvider>
          <AppNavigator /> {/* 渲染抽离后的路由组件 */}
        </PaperProvider>
      </PersistGate>
    </Provider>
  );
}

原理说明

Redux的useSelector、useDispatch等Hook必须在被<Provider>包裹的组件内部使用,因为这些Hook依赖Redux提供的上下文(Context)。你原代码中useSelector在<Provider>渲染前就执行,自然无法获取到Store上下文,抽离组件后,AppNavigator处于<Provider>范围内,就能正常访问Store了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 21:35:36