始终未定义this.props.navigation

时间:2020-09-10 09:59:29

标签: navigation react-navigation

我总是收到错误(TypeError:undefined不是对象(正在评估'_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",
        }}
      />
    );
  }
}

1 个答案:

答案 0 :(得分:0)

我添加了这些并且它起作用了:

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>
  );
}