我正在尝试从反应导航路线道具访问props.route.params.data信息,但是当我尝试在屏幕上输出它时,它只是说TypeError:undefined不是一个对象(评估{{1} })。我知道我正确地遵循了该props.routes.params
对象的路径,因为我在控制台上进行了console.log记录并输出了该数据。但是,当我想将其放在用户界面上时,会出现该错误。一直在线搜索,但没人遇到相同的问题,可能是因为使用react stack navigator v5获取参数的方法是通过route.params,而v5几个月前就问世了。因此,我将在下面的代码以及console.log屏幕,错误消息以及我从中选择的对象中发布代码。谢谢!
data
答案 0 :(得分:1)
由于您是主屏幕上的pokedetails,因此出现以下错误,只有导航到pokedetails屏幕才能获得数据道具,您可以执行以下操作:
像这样更改您的Home.js:
import React, { useState } from "react";
import { View, Text , Button, FlatList, ActivityIndicator, TouchableOpacity, Image } from "react-native";
import PokeDetails from "./Pokedetails";
import { useRoute } from '@react-navigation/native';
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
dataSource: [],
}
}
componentDidMount() {
fetch(`https://pokeapi.co/api/v2/pokemon/?limit=20`)
.then((res)=> res.json())
.then((response)=> {
this.setState({
isLoading: false,
dataSource: response.results,
})
console.log("RESPONSE",response)
console.log("RESPONSE.RESSSULTS",response.results)
})
}
render() {
const showIndicator = this.state.isLoading == true ? <ActivityIndicator size="large" color="#0000ff" /> : null;
return(
<View>
<View>{showIndicator}</View>
<FlatList
keyExtractor={(item, index) => item.name}
numColumns={1}
data={this.state.dataSource}
renderItem={({item})=>
<TouchableOpacity onPress={()=> this.props.navigation.navigate('PokeDetails',
{data:"hello", imageUrl:`https://projectpokemon.org/images/normal-sprite/${item.name}.gif`})}>
<PokeDetails imageUrl={`https://projectpokemon.org/images/normal-sprite/${item.name}.gif`} name={item.name}/>
</TouchableOpacity>
}/>
<Button onPress={()=> this.props.navigation.navigate("About")} title="Go to about"/>
</View>
)
}
}
export default Home;
这里我只是通过了imageUrl以供参考。
将您的pokedetails.js更改如下:
import React from "react";
import { View, Text , Image, Button} from "react-native";
import { TouchableOpacity } from "react-native-gesture-handler";
import { useRoute } from '@react-navigation/native';
const PokeDetails =(props)=> {
console.log("props is",props);
if(props.navigation == undefined)
{
return(
<View>
<Image source={{uri: props.imageUrl}} style={{height: 50, width: 50}}/>
<Text>{props.name}</Text>
</View>
)
}
else{
return(
<View>
<Image source={{uri: props.route.params.imageUrl}} style={{height: 50, width: 50}}/>
<Text>{props.route.params.data}</Text>
</View>
)
}
}
export default PokeDetails;
这里,我只是添加一个if条件来检查是否从另一个屏幕导航了该屏幕。
加载主屏幕后,将显示以下内容:
单击“ bulbassor”后,您将导航到“ pokedetails”屏幕,其中在此显示要通过导航发送的详细信息:
希望这会有所帮助!