2017-10-17 29 views
0

我使用反應原生在與世博會和我的iphone 5與世博會應用程序的Windows。 我希望從Web服務API獲取數據,與之反應原住民我有此錯誤:App.js:意外的標記(15:6) 我想從web服務反應本機語法錯誤意想不到的令牌獲取api

這裏得到的迴應陣列是我的代碼:

import React, { Component } from 'react' 
import { 
    AppRegistry, 
    StyleSheet, 
    Text, 
    View 
} from 'react-native' 

export default class App extends Component { 



fetch('https://httpbin.org/get').then(function (response) { 
     return response; 
     }).then(function (response) { 
     setTimeout(function() { 
      main.setState({ 
      infoStatus: 'loaded' 
      }); 
     }, 300); 
     return response.json(); 
     }).then(function (data) {alert(data); 
     main.setState({ 
      city: data.name, 
      country: data.sys.country, 
      temperature: data.main.temp, 
      humidity: data.main.humidity, 
      wind: data.wind.speed 
     }); 
     }).catch(function() { 
     main.setState({ 
      infoStatus: 'error' 
     }); 
     }); 

    render() { 
    return (
     <View style={styles.container}> 
     <Text style={styles.welcome}> 
      Welcome 
     </Text> 
     </View> 
    ) 
    } 
} 

const styles = StyleSheet.create({ 
    container: { 
    flex: 1, 
    justifyContent: 'center', 
    alignItems: 'center', 
    backgroundColor: '#F5FCFF', 
    }, 
    welcome: { 
    fontSize: 20, 
    textAlign: 'center', 
    margin: 10, 
    }, 
}) 
+1

類不能有任意JavaScript在他們。你必須把你的代碼放在方法裏面https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes – azium

回答

0

您可能希望將代碼放入componentDidMount生命週期掛鉤。

class App extends Component { 
    componentDidMount() { 
    fetch() ... 
    } 

    render() { 
    } 
} 
0

代碼中的對象'main'是什麼? 和你爲什麼使用setTimeout?

你需要把獲取的方法調用裏面... 通常你會做它在componentWillMount 例如:

export default class App extends Component { 
    componentWillMount() { 
    fetch('https://httpbin.org/get') 
    .then(function(response) { 
     this.setState({ infoStatus: 'loaded' }); 
     return response.json(); 
    }) 
    .then(function(data) { 
     this.setState({ 
     city: data.name, 
     country: data.sys.country, 
     temperature: data.main.temp, 
     humidity: data.main.humidity, 
     wind: data.wind.speed 
     }); 
    }) 
    .catch(function() { 
     main.setState({ 
     infoStatus: 'error' 
     }); 
    }); 
    } 
    render() {...} 
}