【问题标题】:when I'm using DrawerItemList the app crashes当我使用 DrawerItemList 时,应用程序崩溃
【发布时间】:2022-08-03 12:01:47
【问题描述】:

我正在尝试使用反应导航创建抽屉菜单。我想使用自定义 DrawerContent,当我使用应用程序时,应用程序崩溃并出现以下错误:“未定义不是对象(评估 \'state.routes\')\”。如果我评论这个特定的行,应用程序就会运行。

这是我的抽屉内容:

import {
  DrawerContentScrollView,
  DrawerItem,
  DrawerItemList,
} from \"@react-navigation/drawer\";
import React from \"react\";
import { Text, View, StyleSheet } from \"react-native\";

export default function DrawerContent(props) {
  return (
    <View style={{ flex: 1 }}>
      <DrawerContentScrollView
        {...props}
        contentContainerStyle={{ backgroundColor: \"#000\" }}
      >
      <DrawerItemList {...props} />
      </DrawerContentScrollView>
    </View>
  );
}

这是我的 App.js(导航在哪里):

import React from \"react\";
import Home from \"./src/screens/Home.js\";
import { NavigationContainer } from \"@react-navigation/native\";
import { createDrawerNavigator } from \"@react-navigation/drawer\";
import DrawerContent from \"./src/components/DrawerContent.js\";

const Drawer = createDrawerNavigator();

export default function App() {
  return (
    <NavigationContainer>
      <Drawer.Navigator
        drawerContent={() => <DrawerContent />}
        initialRouteName=\"Home\"
      >
        <Drawer.Screen
          options={{ headerShown: false }}
          name=\"Home\"
          component={Home}
        ></Drawer.Screen>
      </Drawer.Navigator>
    </NavigationContainer>
  );
  • 您还可以共享顶级组件吗?我在这里看不到state.routes
  • 例如,顶级组件是我使用导航容器的地方吗?
  • 请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如它目前所写的那样,很难准确地说出你在问什么。

标签: react-native react-navigation react-navigation-drawer


【解决方案1】:

您期望 DrawerItemList 接收来自 Drawer.Navigator 的全套道具,但您将其传递给 Drawer.Navigator 包装在一个丢弃它收到的所有道具的函数中:

<Drawer.Navigator
  drawerContent={() => <DrawerContent />} // <-- no props passed to DrawerContent
  initialRouteName="Home"
>

您需要通过所有道具:

<Drawer.Navigator
  drawerContent={(props) => <DrawerContent {...props} />} // <-- pass in the props
  initialRouteName="Home"
>

请注意,您可能认为您可以将函数组件传递给 prop,如下所示,它在功能上与上面的相同:

<Drawer.Navigator
  drawerContent={DrawerContent} // <-- will fail with "rules of hooks" errors
  initialRouteName="Home"
>

...但是如果它是一个包含钩子的功能组件,这将失败并出现“无效的钩子调用”错误,因为drawerContent prop treats the passed-in function as a render function, not a function component

【讨论】:

    【解决方案2】:

    我尝试了所有可能的方法来解决这个错误,但最后在重新启动我的电脑后我解决了这个错误。希望它也适用于你

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-12
      • 2016-06-20
      • 2018-04-27
      • 1970-01-01
      • 1970-01-01
      • 2020-02-07
      • 2018-07-23
      相关资源
      最近更新 更多