【问题标题】:Invalid Hook Call when using useSelector in Functional Component在功能组件中使用 useSelector 时挂钩调用无效
【发布时间】:2021-03-26 07:37:57
【问题描述】:

我得到了错误

错误:无效的挂钩调用。 Hooks 只能在函数组件内部调用。

  1. 您的 React 和渲染器版本可能不匹配(例如 React DOM)
  2. 您可能违反了 Hooks 规则
  3. 您可能在同一个应用中拥有多个 React 副本

我不明白。我在整个应用程序中使用useSelector() 没有任何问题。在这个组件中使用它时,它会中断。这是为什么呢?

import { useSelector } from "react-redux";

const DrawerContent = (props) => {
  const someVar = useSelector((state) => state.foo.bar);
  return (
    <DrawerContentScrollView {...props}>
      <Foo>{someVar}</Foo>
      <DrawerItemList {...props}>
        <DrawerItem
          label="Kitten"
          onPress={() => props.navigation.navigate("Cat")}
        />
        <DrawerItem
          label="Doggo"
          onPress={() => props.navigation.navigate("Dog")}
        />
      </DrawerItemList>
    </DrawerContentScrollView>
  );
};

&lt;DrawerContent /&gt;是这样使用的

const DrawerNavigator = () => {
    return <Drawer.Navigator
        drawerContent={props => DrawerContent(props)}>
        <Drawer.Screen name='A' component={TabNavigator} />
        <Drawer.Screen name='B' component={AStack} />
        <Drawer.Screen name='C' component={BStack} />
    </Drawer.Navigator>
}

【问题讨论】:

  • 你尝试过导入 React 吗?
  • 我通常这样做:useSelector(state => state.reduceUser.userName)
  • @James 那 (menuComponent={props =&gt; &lt;MainMenu {...props}/&gt;) 实际上就是我所拥有的。
  • @Stophface DrawerContent 是如何呈现的(假设您从那里得到错误)?它是如何渲染的父级和它的父级...如果您通过在渲染周期之外调用它的函数来渲染功能组件,您可能会遇到此错误。如果您将此组件创建为您导入的可重复使用的单独项目,那么您可能有可能导致此错误的不匹配的 React 版本。
  • @HMR 正如我所说,我在整个应用程序中都使用了钩子,它们可以工作。所以我不太可能说不匹配的react 版本。我添加了DrawerComponent 的使用方式。

标签: javascript reactjs react-redux react-hooks


【解决方案1】:

您像普通函数一样调用 DrawerContent,而不是将其用作标记。这样一来,DrawerContent 就不会有生命周期或状态,它只是一个普通的函数,返回东西。你需要使用 JSX 语法来调用它,然后 DrawerContent 会有生命周期,你可以在那里使用Selector。

const DrawerNavigator = () => {
    return <Drawer.Navigator
        drawerContent={props => DrawerContent(props)}>  // This just call DrawerContent as a normal function with no life cycle and state
        <Drawer.Screen name='A' component={TabNavigator} />
        <Drawer.Screen name='B' component={AStack} />
        <Drawer.Screen name='C' component={BStack} />
    </Drawer.Navigator>
}

解决方案:

const DrawerNavigator = () => {
    return <Drawer.Navigator
        drawerContent={props => <DrawerContent {...props} />}>  // Now your component has life cycle
        <Drawer.Screen name='A' component={TabNavigator} />
        <Drawer.Screen name='B' component={AStack} />
        <Drawer.Screen name='C' component={BStack} />
    </Drawer.Navigator>
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 2023-02-09
    • 2021-12-07
    • 1970-01-01
    相关资源
    最近更新 更多