[英]Invalid Hook Call when using useSelector in Functional Component
I get the error我得到错误
Error: Invalid hook call.错误:无效的挂钩调用。 Hooks can only be called inside of the body of a function component.钩子只能在 function 组件的主体内部调用。
- You might have mismatching versions of React and the renderer (such as React DOM)你可能有不匹配的 React 版本和渲染器(例如 React DOM)
- You might be breaking the Rules of Hooks您可能违反了 Hooks 规则
- You might have more than one copy of React in the same app你可能在同一个应用程序中拥有多个 React 副本
Which I do not understand.我不明白。 I am using useSelector()
throughout my App without any Problems.我在整个应用程序中使用useSelector()
没有任何问题。 And when using it in this component, it breaks.在这个组件中使用它时,它会中断。 Why is that?这是为什么?
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>
);
};
<DrawerContent />
is used like this <DrawerContent />
是这样使用的
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>
}
You're calling DrawerContent like a normal function, not using it as a tag.您像普通的 function 一样调用 DrawerContent,而不是将其用作标签。 As a result, DrawerContent will not have life cycle or state, it's just a normal function, return stuff.结果,DrawerContent不会有生命周期或者state,它只是一个普通的function,退货。 You need to invoke it by using JSX syntax, then DrawerContent will have life cycle and you can useSelector there.您需要使用 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>
}
Solution:解决方案:
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>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.