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

时间:2020-03-18 01:44:20

标签: javascript react-native react-navigation-stack

因此,我正在尝试访问通过this.props.navigation.push发送的参数,但无法终生解决。我总是得到undefined不是对象。任何帮助表示赞赏。

App.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(发送参数的屏幕):

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(我要通过其访问参数的屏幕):

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'
    }
})

顺便说一句,如果您发现其他可能导致错误的内容,请告诉我。谢谢

1 个答案:

答案 0 :(得分:2)

首先,导航参数应该是object。因此,您必须传递这样的参数:

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

然后,您可以通过this.props.navigation.getParam()方法访问导航参数。所以代替

movies = this.props.route.params.movies

您应该使用:

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