简体   繁体   English

反应本机语法错误意外的令牌获取api

[英]react native syntax error unexpected token fetch api

I use react native on windows with Expo and my iphone 5 with expo app. 我在Windows上使用Expo本机在Windows上使用本机反应,而我的iPhone 5在EXPO应用程序上使用。 I wish to get data from a webservice api , with React Native i have this error : App.js: unexpected token(15:6) I wish to get the response array from the webservice 我希望从Web服务api获取数据,使用React Native我遇到以下错误:App.js:意外令牌(15:6)我希望从Web服务获取响应数组

Here is my code : 这是我的代码:

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,
  },
})

You may want to put your code into componentDidMount lifecycle hook. 您可能需要将代码放入componentDidMount生命周期挂钩中。

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

  render () {
  }
}

What is the object 'main' in your code? 您的代码中的“主要”对象是什么? and why do you use setTimeout? 为什么要使用setTimeout?

you need to put the fetch call inside a method... normally you will do it in componentWillMount for example: 您需要将fetch调用放入方法中...通常,您将在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() {...}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM