简体   繁体   English

似乎无法访问反应导航中的参数

[英]Can't seem to access the params in react navigation

So I'm trying to access params sent through this.props.navigation.push but can't figure it out for the life of me.所以我试图访问通过 this.props.navigation.push 发送的参数,但我一生都无法弄清楚。 I always get undefined is not an object.我总是得到 undefined 不是一个对象。 Any help is appreciated.任何帮助表示赞赏。

App.js:应用程序.js:

import React from 'react';
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native';
import { createStackNavigator } from '@react-navigation/stack'

import { SearchScreen } from './screens/SearchScreen.js'
import { ResultsScreen } from './screens/ResultsScreen.js'
import { NavigationContainer } from '@react-navigation/native'

const AppNavigator = createStackNavigator()

export default class App extends React.Component {
  render() {
    return (
      <NavigationContainer>
        <AppNavigator.Navigator>
          <AppNavigator.Screen name="ResultsScreen" component={ResultsScreen} />
          <AppNavigator.Screen name="SearchScreen" component={SearchScreen} />
        </AppNavigator.Navigator>
      </NavigationContainer>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

SearchScreen (screen through which params are sent): SearchScreen(发送参数的屏幕):

import React from  'react'
import { KeyboardAvoidingView, TextInput, Button, StyleSheet } from 'react-native'
import { url } from '../mockData.js'

export class SearchScreen extends React.Component {
    state = {
        title: "",
        year: 0,
        ID: "",
        isValid: false
    }

    componentDidUpdate(prevProps, prevState) {
        if (this.state.title !== prevState.title || 
            this.state.year !== prevState.year ||
            this.state.ID !== prevState.ID) 
        {
            this.isInputValid()
        }
    }

    getHandler = key => val => {
        this.setState({ [key]: val })
    }

    handleTitleChange = this.getHandler('title')
    handleYearChange = this.getHandler('year')
    handleIDChange = this.getHandler('ID')

    handleSubmit = () => {
        movieArr = [this.state.title, this.state.year, this.state.ID]
        movies = getMovies(movieArr)
        this.props.navigation.push('ResultsScreen', {movies: movies})
    }
    isInputValid = () => {
        if (this.state.title || this.state.year || this.state.ID) {
            this.setState({ isValid: true })
        }
    }

    render() {
        return (
            <KeyboardAvoidingView behavior="padding">
                <TextInput 
                    placeholder='title'
                    value={this.state.title} 
                    onChangeText={this.handleTitleChange} 
                    style={styles.input}
                />
                <TextInput 
                    placeholder='phone'
                    value={this.state.phone} 
                    onChangeText={this.handlePhoneChange} 
                    style={styles.input}
                    keyboardType='numeric'
                />
                <TextInput 
                    placeholder='imdb ID'
                    value={this.state.ID} 
                    onChangeText={this.handleIDChange} 
                    style={styles.input}
                />
                <Button 
                    title='submit'
                    onPress={this.handleSubmit}
                    disabled={!this.state.isValid}
                />
            </KeyboardAvoidingView>
        )
    }
}
async function getMovies(info) {
    if (info[0] !== "") {
        if (info[2] !== "") {
            url += `&t=${info[0]}&i=${info[2]}`
        } else { 
            url += `&s=${info[0]}`
        }
    }
    if (info[1] !== 0) {
        url += `&y=${info[1]}`
    }

    return await fetch(url)
}

styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
    },
    input: {
        borderWidth: 1,
        borderColor: 'black',
        minHeight: 20,
        minWidth: 100
    }
})

ResultsScreen (screen through which I want to access params): ResultsScreen(我想通过它访问参数的屏幕):

import React from 'react'
import {Text, StyleSheet} from 'react-native'
import MovieSections from '../MovieSections.js'

export class ResultsScreen extends React.Component {
    movies = this.props.navigation.getParam('movies')

    validate = () => {
        if (this.movies.Error === "Incorrect IMDb ID.") {
            return <Text>The imdbID is invalid...Check for any typos.</Text>
        } else if (this.movies.Error === "Movie not found!") {
            return <Text>The movie wasn't found 😢... See if you entered the information correctly!</Text>
        }
    }

    goToDetails = () => {
        this.props.navigation.navigate('SearchScreen')
    }

    render() {
        return(
            <MovieSections movies={this.props.movies} goToDetails={this.goToDetails}/>
        )
    }
}

styles = StyleSheet.create({
    error: {
        color: 'red',
        alignSelf: 'center'
    }
})

BTW, if you find anything else that might cause an error, please tell me.顺便说一句,如果您发现其他任何可能导致错误的内容,请告诉我。 Thanks谢谢

First of all navigation parameter should be object.首先导航参数应该是对象。 So you have to pass parameter like this :所以你必须像这样传递参数:

this.props.navigation.push('ResultsScreen',{
  movies: movies
})

Then you can access navigation parameter by this.props.navigation.getParam() method.然后你可以通过this.props.navigation.getParam()方法访问导航参数。 So instead of所以代替

movies = this.props.route.params.movies

you should use :你应该使用:

movies = this.props.navigation.getParam('movies');

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

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