React Native 0.64.2搭配React-Redux7.2.4访问props报undefined is not an object错误
核心问题原因
- 函数组件不存在
this对象,你的代码中使用this.props.syncedDate取值属于Class类组件的写法,在函数组件中不生效,props会直接作为函数的第一个参数传入。 - 你同时导出了未连接Redux的命名组件
DetailsScreen和已完成Redux连接的默认组件,如果引入组件时使用了命名引入的写法,实际渲染的是没有注入Redux属性的版本,也会导致取值为空。
修复方案
方案1:保留connect写法适配函数组件
修改业务组件代码如下:
import React from 'react'; import type { Node } from 'react'; import { Text, View, } from 'react-native'; import { connect } from 'react-redux'; // 将syncedDate从参数中直接解构,不需要通过this取值 const DetailsScreen = ({ route, navigation, syncedDate }) => { const { name } = route.params; return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <Text>Details List</Text> <Text>Incoming param: {JSON.stringify(name)}</Text> <Text>SyncedDate: {syncedDate}</Text> </View> ); }; const mapStateToProps = (state) => { return { syncedDate: state.projects.syncedDate } }; // 仅默认导出连接后的组件,避免多导出导致的引入错误 export default connect(mapStateToProps)(DetailsScreen);
引入组件时使用默认引入写法即可:
import DetailsScreen from './你的组件文件路径';
方案2:使用Redux Hooks(更适配函数组件的推荐写法)
不需要写connect和mapStateToProps,直接用Redux提供的钩子取值,代码更简洁:
import React from 'react'; import type { Node } from 'react'; import { Text, View, } from 'react-native'; // 引入Redux提供的useSelector钩子 import { useSelector } from 'react-redux'; const DetailsScreen = ({ route, navigation }) => { const { name } = route.params; // 直接通过钩子从store中取值 const syncedDate = useSelector(state => state.projects.syncedDate) return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <Text>Details List</Text> <Text>Incoming param: {JSON.stringify(name)}</Text> <Text>SyncedDate: {syncedDate}</Text> </View> ); }; export default DetailsScreen;
内容的提问来源于stack exchange,提问作者Leland T Long
相关产品推荐
相关产品推荐

