繁体   English   中英

尝试在反应本机堆栈导航器 v5 中访问 route.params

[英]Trying to access route.params in react native stack navigator v5

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

// 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;

在此处输入图像描述 在此处输入图像描述

您收到以下错误,因为您在主屏幕中是 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 屏幕,此处显示您通过导航发送的详细信息:

在此处输入图像描述

希望这可以帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM