首页 > 解决方案 > this.props.navigation 始终未定义

问题描述

我总是收到错误( TypeError: undefined is not an object (evalating '_this.props.navigation.navigate'))。我尝试了很多解决方案,但都没有奏效。所有导致相同的错误。你能检查我的代码并告诉我有什么问题吗?

这是我的代码。你能帮我吗:

import React, {Component} from 'react';
import { FlatList,TouchableOpacity, Text, Button, View,Image, ActivityIndicator, Platform} from 'react-native';

export default class Project extends Component {
 

  constructor(props)
  {
    super(props);
    this.state = { 
    isLoading: true,
    }

  }

  render() {

    if (this.state.isLoading) {
      return (
        <View style={{flex: 1, paddingTop: 20}}>
          <ActivityIndicator />
        </View>
      );
    }

    return (

<View style={styles.MainContainer} >

 <FlatList       
          data={ this.state.dataSource }        
          ItemSeparatorComponent = {this.FlatListItemSeparator}
          renderItem={({item}) => 
            <TouchableOpacity onPress={ () => this.props.navigation.navigate('DetailPage') 
           
            } style={{flex:1, flexDirection: 'row'}}>                
            <Text style={styles.FlatListItemStyle}  > {item.title} </Text>
            </TouchableOpacity>
        }
        keyExtractor={(item, index) => index}    
 />
</View>           
    );
  }

  componentDidMount() {
       return fetch('http://192.152.79.6/lcu/pages/testReactNative')
         .then((response) => response.json())
         .then((responseJson) => {
           this.setState({
             isLoading: false,
             dataSource: responseJson
           }, function() {
            
           });
         })
         .catch((error) => {
           console.error(error);
         });
     }

FlatListItemSeparator = () => {
    return (
      <View
        style={{
          height: 1,
          width: "100%",
          backgroundColor: "#607D8B",
        }}
      />
    );
  }
}

标签: navigationreact-navigation

解决方案


我已经添加了这些并且它有效:

import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

在 App.js 文件的末尾:

const Stack = createStackNavigator();

function MyStack() {
  return (
    <Stack.Navigator>
      <Stack.Screen name="Home" component={Project} />
      <Stack.Screen name="DetailPage" component={DetailPage} />
    </Stack.Navigator>
  );
}
export default function App() {
  return (
    <NavigationContainer>
      <MyStack />
    </NavigationContainer>
  );
}

推荐阅读