开发者问题收集

将值从一个屏幕移动到另一个屏幕错误:未定义不是一个对象(评估“route.params.message”)

2020-02-13
23976

我尝试在 React Native 中通过将值从一个屏幕传递到另一个屏幕来从一个屏幕导航到另一个屏幕,但是我收到了上述错误。理想情况下,我希望从平面列表中发送值,我试图实现一个可点击的平面列表,它将参数从选定行传递到另一个屏幕。

//index.js

import React from 'react';
import { StyleSheet, Button, Text, View, FlatList, TouchableHighlight } from 'react-native';

const ComponentsScreen = ({ navigation }) => {

  //example for detail scree
  return (
    <View>
    <FlatList
           data={[
             { key: 'Task 1' },
             { key: 'Task 2' },
             { key: 'Task 3' },
             { key: 'Task 4' },
             { key: 'Task 5' },
           ]}
           renderItem={({ item }) => {
               return (
                 <TouchableHighlight
                        onPress={() =>
                        navigation.navigate('Next', { message: 'hello from screen 1' })}
                 >
                      <Text >{item.key}</Text>
                 </TouchableHighlight>
               );
             }
           }

    />

    <Button
        onPress={() => navigation.navigate('NextScreen')}
        title="Go to ImageScreen"
    />
    </View>
  );
};
const styles = StyleSheet.create({
textStyle: {
  fontSize: 30
}
});

export default ComponentsScreen;

//NextScreen.js

  import React from 'react';
import { Text, View } from 'react-native';

//example for detail screen
const NextScreen = (route) => {
const { message } = route.params;

    return (
        <View>
          <Text>message: {JSON.stringify(message)}</Text>
        </View>
    );
};

export default NextScreen;

app.js

import React, { Component } from 'react';
import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
import Index from './screens/Index';
import NextScreen from './screens/NextScreen';


const navigator = createStackNavigator({
  Home: Index,
  Next: NextScreen
},
{
  initialRouteName: 'Home',
  defaultNavigationOptions: {
    title: 'App'
  }
}
);

export default createAppContainer(navigator);
3个回答

如果您想要接收一个屏幕到另一个屏幕的参数,您需要使用 getparam 函数,例如: const message = navigation.getParam('message');

hlebon
2020-02-13

最终找到了在路线之间移动值的方法

 navigation.navigate('RouteB', {
        screen: 'ScreenC',
        params: { param1: "foo", param2: "bar" }
      })

然后您可以在 ScreenC 中使用

const ScreenC = ({ navigation, route }) => {
  const { param1, param2 } = route.params
....
}
获取这些值
msalihbindak
2020-09-30

尝试使用 encodeURIComponent(this.props.navigation.getParam('message'); 或 encodeURIComponent(this.props.navigation.Param('message');

user2130733
2020-04-18