undefined - параметры, передаваемые в App.js с заставки - PullRequest
0 голосов
/ 31 мая 2019

Добавлен экран-заставка для реакции собственного приложения (0.59) с реагирующей навигацией (3.9) на эмуляторе Android, чтобы получить локальное значение и передать его обратно в App.js для маршрутизации.Вот компонент SplashScreen:

import React, { Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';
import helper from "../../lib/helper";

class SplashScreen extends React.Component {
    ......

    async componentDidMount() {
        const data = await this.performTimeConsumingTask();
        this.props.navigation.navigate('App', {params  : data});  //<<<===pass the params to App
        }

    render() {
        return (
          <View style={styles.viewStyles}>
            <Text style={styles.textStyles}>
              Blitz Reading
            </Text>
          </View>
        );
      }
    }

    const styles = {
      .......
    }

    export default SplashScreen;

Локальные данные извлекаются после монтирования заставки.Затем извлеченные data передаются обратно в App.js в качестве параметров.Вот App.js:

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';
.....
import SplashScreen from "./src/components/splashscreen/SplashScreen";


const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu',
  android:
    'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});

//socket.io
const socket = io(GLOBAL.BASE_URL, {
  //const socket = io(GLOBAL.BASE_URL, {
    transports: ['websocket'],
    jsonp: false
  });
console.log("socket id in App.js : ", socket.id);    

socket.on('disconnect', (reason) => {
  // ...
  if (reason === 'io server disconnect') {

    socket.connect();
  }
  // else the socket will automatically try to reconnect
});

const ChatWithSocket = (props) => (<Chat {...props} socket={socket} />)

//create the navigator
const EventStack = createStackNavigator(
  {
    Event:  Event,
    NewEvent: NewEvent,
    Chat: {
      screen: ChatWithSocket,

    },
    Signup: Signup,
    Verif1: Verif1,

  },  {
    initialRouteName: 'Verif1',
  } 
);

const UserStack = createStackNavigator(
  {
    NewUser: NewUser,
    EditUser: EditUser,    
  }, {
      initialRouteName: "NewUser",
  }

);

const bottomTabNav = createBottomTabNavigator(
    {
      Event: {screen: EventStack},
      User: {screen: UserStack},
    },
    {
        defaultNavigationOptions: ({ navigation }) => ({
          tabBarIcon: ({ focused, tintColor }) => {
            const { routeName } = navigation.state;
            console.log("In App.js, props is : ", this.props);  //<<==Value?
            let iconName;
            if (routeName === 'Event') {
              iconName = `ios-information-circle${focused ? '' : '-outline'}`;
            } else if (routeName === 'NewUser') {
              iconName = `ios-options${focused ? '' : '-outline'}`;
            }


            return <Text>Hello the world!</Text>
          },
        }),
        tabBarOptions: {
          activeTintColor: 'tomato',
          inactiveTintColor: 'gray',
        },
      }
    );

const InitialNavigator = createSwitchNavigator({
  Splash: SplashScreen,
  App: bottomTabNav,
});


const AppContainer = createAppContainer(InitialNavigator);

export default AppContainer;

Но вывод this.props равен undefined:

05-30 19:01:55.893  8312  8366 I ReactNativeJS: 'In App.js, props is : ', undefined
05-30 19:01:55.894  8312  8366 I ReactNativeJS: 'In App.js, props is : ', undefined
05-30 19:01:56.016  8312  8366 I ReactNativeJS: 'In App.js, props is : ', undefined
05-30 19:01:56.017  8312  8366 I ReactNativeJS: 'In App.js, props is : ', undefined

Я также попытался navigation.state.params, и это undefined какЧто ж.Как получить доступ к параметрам, переданным на App.js?

1 Ответ

1 голос
/ 31 мая 2019

Поскольку вы перемещаетесь и передаете параметры в навигаторы вкладок, вы должны извлечь их из родительского маршрутизатора

defaultNavigationOptions: ({ navigation }) => ({
  tabBarIcon: ({ focused, tintColor }) => {
    ...
    const yourParams = navigation.dangerouslyGetParent().getParam('yourParamHere')
    ...
  },
}),
...