Undefined 不是评估 route.params.input 的对象。在组件之间传递数据时出错。REACT NATIVE
2021-11-17
2079
将文本输入从一个屏幕传递到另一个屏幕时出现上述错误。有趣的是,启动应用程序时出现错误并导致应用程序崩溃。但是,如果我删除以下代码中的行:const { input } = route.params; 运行应用程序。它不会崩溃。因此,我可以使用文本输入导航到屏幕。输入一些文本。然后重新添加行 const { input } = route.params; 应用程序可以运行,并且数据可以从一个屏幕传递到另一个屏幕。如果我刷新应用程序,它就会崩溃。我尝试对一些数据进行硬编码,因此启动应用程序时 Textinput 不为空。这不起作用,应用程序在启动时仍然崩溃。下面是我的代码?知道为什么会发生上述行为吗?
在这里,我在屏幕上导航:Opci Podaci,文本输入位于其中,并且还显示数据{input}:
import React, {useContext, useState} from "react";
import styled from "styled-components";
import { Text, View, ScrollView} from "react-native";
import {List} from "react-native-paper";
import { OpciPodaciOglasInput } from "../../components/iznajmljivanje.PodaciInput/opciPodaciInput";
export const IznajmiScreen = ({navigation, route}) => {
const { input } = route.params;
return (
<>
<SectionContainer>
<ScrollView>
<List.Accordion
title="Detalji Oglasa"
left={(props) => <List.Icon {...props} icon="car-sports" />}
expanded={detaljiExpanded}
onPress={() => setDetaljiExpanded(!detaljiExpanded)}
>
<List.Item title="Unesi Opis..."
onPress={()=>navigation.navigate("Opci Podaci")} />
<List.Item />
</List.Accordion>
<Text>{input}</Text>
</ScrollView>
</SectionContainer>
</>
);
};
文本输入屏幕(代码中的Opci podaci):
import React, {useState} from "react";
import styled from "styled-components";
import {TextInput, View, StyleSheet, Text, Button} from "react-native";
export const OpciPodaciOglasInput = ({navigation}) => {
const [input, setInput] = useState("");
return(
<>
<Button title="Save"
onPress={()=>navigation.navigate("Rent a car", {input})}/>
<InputContainer>
<Text>Unesi Podatke</Text>
<TextInput style={styles.input}
placeholder="300 rijeci maximum"
multiline = {true}
maxLength={300}
onChangeText={(text)=> setInput(text)}
returnKeyType='done'
value={input}
onSubmitEditing={()=>{
navigation.navigate('Rent a car',{input});
setInput("");
}}
/>
</InputContainer>
</>
);
};
以及我的导航:
import React from "react";
import { Button } from "react-native";
import {createStackNavigator, CardStyleInterpolators} from "@react-navigation/stack";
import { IznajmiScreen } from "../screens/tabNavigation.screens/iznajmiScreen";
import { OpciPodaciOglasInput } from "../components/iznajmljivanje.PodaciInput/opciPodaciInput";
const IznajmiStack = createStackNavigator();
export const IznajmiScreenNavigator = ({ route, navigation }) => {
return (
<IznajmiStack.Navigator
screenOptions="screen"
screenOptions={{
cardStyleInterpolator: CardStyleInterpolators.forHorizontalIOS,
}}
>
<IznajmiStack.Screen
options={{headerRight:()=>(<Button title="Predaj Oglas"
onPress={()=>{}}/>)}} //TODO on PRESS
name="Rent a car"
component={IznajmiScreen}
/>
<IznajmiStack.Screen name="Opci Podaci" component={OpciPodaciOglasInput}/>
</IznajmiStack.Navigator>
);
};
1个回答
问题在于
const { input } = route.params;
这一行 - 在 react-navigation 填充
route
对象之前,尝试引用其嵌套属性时会出错。安全访问
route
对象将阻止这种情况,即
const { input } = route?.params || {};
Abe
2021-11-18