javascript - 尝试在React Native Stack Navigator v5中访问route.params

标签 javascript reactjs database react-native react-navigation

我试图从 react 导航路由 Prop 中访问 props.route.params.data 信息,但是当我尝试将其输出到屏幕上时,它只是说 TypeError: undefined is not an object(evaluating props .routes.params)。我知道我已经正确遵循了该 data 对象的路径,因为我在控制台上 console.log 它并输出该数据。然而,当我想把它放在用户界面上时,它给了我这个错误。在网上搜索过,但没有人遇到同样的问题,可能是因为使用react stack navigator v5获取参数的方式是通过route.params,而v5几个月前就出来了。因此,我将在下面发布我的代码以及 console.log 屏幕、错误消息以及我从中选择的对象。谢谢!

// App.js

import 'react-native-gesture-handler';
import React from 'react';
import { View , StyleSheet } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import About from "./screens/About";
import Home from "./screens/Home";
import PokeDetails from "./screens/PokeDetails"
import { createStackNavigator } from '@react-navigation/stack';



const App =()=> {

  const Stack = createStackNavigator();

  return(
    <View style={styles.container}>
      <NavigationContainer>
        <Stack.Navigator>
          <Stack.Screen name="Home" component={Home}/>
          <Stack.Screen name="PokeDetails" component={PokeDetails}/>
          <Stack.Screen name="About" component={About}/>
        </Stack.Navigator>
      </NavigationContainer>
    </View>
  )
}


const styles = StyleSheet.create({
  container: {
    flex: 1
  }
})
  


export default App;



// Home.js


import React, { useState } from "react";
import { View, Text , Button, FlatList, ActivityIndicator, TouchableOpacity, Image } from "react-native";
import { GlobalStyles } from "../styles/GlobalStyles";
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 style={GlobalStyles.container}>
                <View style={GlobalStyles.activityIndicator}>{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"})}>
                        <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;


// PokeDetails.js

import React from "react";
import { View, Text , Image, Button} from "react-native";
import {GlobalStyles} from "../styles/GlobalStyles";
import { TouchableOpacity } from "react-native-gesture-handler";
import { useRoute } from '@react-navigation/native';



const PokeDetails =(props)=> {
   
    console.log(props)
    console.log(props.route.params.data, "PROPSSSSSSSSSSS");
    
        return(
            <View style={GlobalStyles.container}>  
                    <Image source={{uri: props.imageUrl}} style={{height: 50, width: 50}}/>
                    <Text>{props.route.params.data}</Text>
            </View>
        )
    

}
    


export default PokeDetails;

enter image description here enter image description here

最佳答案

您收到以下错误,因为您在主屏幕中显示了 pokedetails,只有导航到 pokedetails 屏幕时才能获取数据 Prop ,您可以执行以下操作:

像这样更改你的 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 条件来检查加载的屏幕是否是从另一个屏幕导航的。

当主屏幕加载时,它会是这样的:

enter image description here

点击bulbassor后,您将导航到pokedetails屏幕,此处显示您通过导航发送的详细信息:

enter image description here

希望这有帮助!

关于javascript - 尝试在React Native Stack Navigator v5中访问route.params,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61486141/

相关文章:

javascript - 动态javascript加载并订阅基于数据的事件?

javascript - 在 JavaScript 中通过 JDBC 连接到 mysql

database - Select Count(*) 在 postgres 数据库上从 <30s 增加到 ~8 分钟 - 391K 行

php - 如何将部分字符串与mysql中的大型数据库进行比较

javascript - 将 SVG dataUrl 转换为 base64

javascript - API 响应显示在 console.log 中但不显示在 React 页面上

javascript - 如果 props 改变,React 会重新评估 useRef

javascript - contact.map 不是一个函数

android - 我应该使用本地数据库并在应用内购买后切换到 Firestore 吗?

javascript - 编码问题,无法用 API 元素创建数组,Reactjs