React Native类组件中Redux无法使用,触发Invalid hook call错误
解决React Native类组件中Redux Hooks触发的"Invalid hook call"错误
错误核心原因
useDispatch和useSelector是React Hooks,只能在函数组件的顶层作用域调用,类组件不支持使用Hooks,这直接违反了Hooks的使用规则,导致报错。
方案一:将类组件转为函数组件(推荐)
Redux Toolkit设计时更适配函数组件+Hooks的写法,转成函数组件是最简洁的解决方式,同时修正代码里的其他小问题:
修改后的inspectionView.jsx:
import React from "react"; import { Text, View, TouchableOpacity } from "react-native"; import { useSelector, useDispatch } from 'react-redux'; import { incrementByAmount, selectCount } from '../redux/slice.js'; export default function InspectionList() { const dispatch = useDispatch(); const count = useSelector(selectCount); return ( <View> <Text>inspection view</Text> <TouchableOpacity onPress={() => dispatch(incrementByAmount("hello world"))} style={{ padding: 10, backgroundColor: '#ccc', marginTop: 10 }} > <Text>Add Amount</Text> </TouchableOpacity> <Text>{count}</Text> </View> ); }
方案二:使用connect高阶组件适配类组件
如果需要保留类组件结构,可以用react-redux提供的connect方法,把Redux的state和dispatch映射到组件的props中:
修改后的inspectionView.jsx:
import React from "react"; import { Text, View, TouchableOpacity } from "react-native"; import { connect } from 'react-redux'; import { incrementByAmount, selectCount } from '../redux/slice.js'; class InspectionList extends React.Component { constructor(props) { super(props); this.state = {}; } render() { const { count, incrementByAmount } = this.props; return ( <View> <Text>inspection view</Text> <TouchableOpacity onPress={() => incrementByAmount("hello world")} style={{ padding: 10, backgroundColor: '#ccc', marginTop: 10 }} > <Text>Add Amount</Text> </TouchableOpacity> <Text>{count}</Text> </View> ); } } // 映射Redux state到组件props const mapStateToProps = (state) => ({ count: selectCount(state) }); // 映射dispatch方法到组件props const mapDispatchToProps = { incrementByAmount }; export default connect(mapStateToProps, mapDispatchToProps)(InspectionList);
额外修正点说明
- React Native中没有Web原生的
<button>组件,改用TouchableOpacity(或Pressable)实现可点击交互 - 原代码中
<Text>{{count}}</Text>是语法错误,应改为<Text>{count}</Text>
内容的提问来源于stack exchange,提问作者Cristian Romero
相关产品推荐
相关产品推荐

