开发者问题收集

react-navigation - 无法读取未定义的属性“navigate”

2017-07-27
1597

我是 React Native 新手,正在尝试创建我的第一个应用程序。所以我有一个问题:

我有 2 个屏幕(使用 react-navigation)。第一个屏幕上会渲染带有旋转器的应用程序徽标(来自 native-base)并同时获取到服务器。并且我只需要在获取结束并处理响应时导航到另一个屏幕。请帮我找出我的错误!

index.ios.js

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TextInput,TouchableHighlight
} from 'react-native';
import { StackNavigator } from 'react-navigation';
import LoadingScreen from './src/screens/LoadingScreen.js';
import MainContainer from './src/screens/MainContainer.js';

export default class Calculator2 extends Component {
  render() {
    return (
      <LoadingScreen/>
    );
  }
}
const AppNavigator = StackNavigator({
  Loading: {
    screen: LoadingScreen
   },
  Main: {
    screen: MainContainer
  }
});

AppRegistry.registerComponent('Calculator2', () => Calculator2);

LoadingScreen.js:

import React, { Component } from 'react';
import {
  AsyncStorage,
  AppRegistry,NetInfo,
  Text,Image,View
} from 'react-native';
import { StackNavigator } from 'react-navigation';
import AppNavigator from '../../index.ios.js';
import { Container, Header, Content, Spinner } from 'native-base';

export default class LoadingScreen extends Component {
  static navigationOptions = {
    title: 'Loading',
  };
  constructor(props){
   super(props);

  }
  componentDidMount(){
    const {navigate} = this.props.navigation;
    fetch('url').then( (response) => {navigate('Main')});
  }
  render() {
    return(
          <View>
            App logo with spinner
          </View>
   );
  }
}

MainContainer.js

import React, { Component } from 'react';
import {
  AppRegistry,Alert,NetInfo,
  StyleSheet,
  Text,
  View,ActivityIndicator,
  TextInput,TouchableHighlight
} from 'react-native';

import { StackNavigator } from 'react-navigation';
import AppNavigator from '../../index.ios.js';

export default class MainContainer extends Component {
  static navigationOptions = {
    title: 'Main',
  };

  render() {
    return (
      <View  style={{flexDirection: 'column'}}>
         ...
      </View>
    );
  }
}

而我得到的只是在 LoadingScreen.componentDidMount 处出现的错误“无法读取未定义的属性‘navigate’”

UPD 实际上我的获取应该是一个获取响应并处理它的函数,它应该等到处理完成:

async function getData(){
    var response = await fetch('url', {
      method: 'GET'
    });
    storage = await response.json(); // storage for response
    regions = Object.keys(storage); // an array of regions names
    console.log(storage, Object.keys(storage));
  };
2个回答

您需要注册 AppNavigator 组件而不是 Calculator2

AppRegistry.registerComponent('Calculator2', () => AppNavigator);
agenthunt
2017-07-27

只需更新您的 LoadingScreen.js 的 componentDidMount 函数如下:

componentDidMount() {
 var self = this;
   fetch('url').then( (response) => {
        self.props.navigation.navigate('Main')
   });
}
Rohan Kangale
2017-07-27