React Native导航传参报错:undefined is not a function 求助
问题分析与解决方案
你遇到的"undefined is not a function"错误由以下代码问题导致,逐一修复即可:
1. ShopListRow 参数传递属性名错误
在infoPressed方法里,你引用了不存在的this.props.place,实际传递给ShopListRow的属性是shop,这会导致参数未定义,进而引发后续错误。同时Image标签存在语法错误,多写了一个Image关键字。
修复ShopListRow.js:
export default class ShopListRow extends Component { infoPressed = () => { this.props.navigation.navigate('ProductDetail', { shop: this.props.shop }) } render() { const { shop, index } = this.props return ( <TouchableHighlight onPress={this.infoPressed}> <View key={shop.id} style={{ backgroundColor: index % 2 === 0 ? '#D3E3EA' : '#B3E3DA' }}> <View style={styles.row}> <View style={styles.edges}> <Text style={styles.sectionTitle}>{shop.title}</Text> <Text style={styles.buttonText}>{shop.description}</Text> </View> <View> <View style={styles.button}> <Image source={{uri: shop.thumbnail}} style={{ margin: 5, height: 120, width: 120 }} /> </View> </View> </View> </View> </TouchableHighlight> ) } }
2. ProductDetail 获取参数的API过时
你使用的navigation.getParam是React Navigation旧版API,新版需通过route.params获取传递的参数。同时直接展示对象会显示[object Object],建议展示具体属性。
修复ProductDetails.tsx:
import { RouteProp } from '@react-navigation/native'; import { StackNavigationProp } from '@react-navigation/stack'; type RootStackParamList = { Home: undefined; ProductDetail: { shop: any }; }; interface Props { navigation: StackNavigationProp<RootStackParamList, 'ProductDetail'>; route: RouteProp<RootStackParamList, 'ProductDetail'>; } export default class ProductDetail extends Component<Props> { render(){ const { shop } = this.props.route.params; return ( <View style={{ backgroundColor: '#D3E3EA', flex: 1 }}> <Text>{shop.title}</Text> <Text>{shop.description}</Text> </View> ) } }
3. ShopList 引用未定义的state
ShopList类组件未定义state,但FlatList中写了extraData={this.state},会导致undefined错误。同时keyExtractor返回的id需确保是字符串类型。
修复ShopList.tsx:
interface ShopListProps { shops: any[]; navigation: any; } class ShopList extends Component<ShopListProps> { render() { const { shops, navigation } = this.props; return ( <FlatList data={shops} renderItem={({ item, index }) => <ShopListRow shop={item} index={index} navigation={navigation} /> } keyExtractor={item => item.id.toString()} initialNumToRender={16} /> ); } } export default ShopList;
4. 补充Home.tsx缺失的导入
确保Home.tsx导入了所有必要的组件:
import React, { useState, useEffect } from 'react'; import { SafeAreaView, useColorScheme, StatusBar, Text } from 'react-native'; import { Colors } from 'react-native/Libraries/NewAppScreen'; import { useNavigation } from '@react-navigation/native'; import ShopList from './ShopList'; // 其余代码保持不变
完成以上修复后,点击列表行即可正常跳转到ProductDetail页面并展示商品信息。
内容的提问来源于stack exchange,提问作者tariq maged
相关产品推荐
相关产品推荐

