navigation - 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",
}}
/>
);
}
}
解决方案
我已经添加了这些并且它有效:
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>
);
}
推荐阅读
- mysql - MySQL 索引未在大型数据库中使用
- linux - 使用 bash 脚本检查网络中不同计算机的信息
- javascript - javascript将本地文件发送到api
- python - 为什么我的 DataFrame 系列给了我单个字符而不是项目?
- javascript - 删除附加的 svg 文本 jquery
- php - Laravel 中 NPM、Composer 和 Bower 的区别?
- google-cloud-platform - 在 Google Cloud 中集群 Eureka 服务器
- excel - 搜索多个条件时 Excel 替代 FIND 函数
- rest - APIRestful 中的资源
- javascript - 不能使用 for 循环来填充完整日历中的数组