我是React Native中的新成員,嘗試創建我的第一個應用程序。所以我有一個問題:react-navigation - 無法讀取undefined的屬性'navigate'
我有2個屏幕(使用react-navigation)。在第一個屏幕上,微調器(從本機基地)呈現應用程序徽標,並同時獲取到服務器。只有當抓取結束並處理響應時,我才需要導航到另一個屏幕。請幫我找到我的錯誤!
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
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));
};
再次感謝您的幫助! – nastassia
也許你可以用我的抓取工具來幫我 - 它應該處理響應並獲取需要渲染選擇器的區域列表。但是在下一個屏幕上的選擇器渲染速度更快,然後列表出現並且具有'undefine'值。 – nastassia
您可以在導航函數中像導航('Main',{regions})'一樣傳遞區域作爲參數,並且您可以在主屏幕中從狀態訪問https://reactnavigation.org/docs/navigators/navigation-prop#state-The-screen's-current-stateroute導航的道具。像'this.props.navigation.state.params.regions'。 –