【问题标题】:react native syntax error unexpected token fetch api反应本机语法错误意外令牌获取api
【发布时间】:2018-03-29 05:17:15
【问题描述】:

我在带有 Expo 的 windows 上使用 react native,在我的 iphone 5 上使用 expo 应用程序。 我希望从 web 服务 api 获取数据,使用 React Native 我有这个错误:App.js: unexpected token(15:6) 我希望从 web 服务中获取响应数组

这是我的代码:

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

【问题讨论】:

标签: javascript json reactjs api react-native


【解决方案1】:

您可能希望将代码放入 componentDidMount 生命周期挂钩中。

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

  render () {
  }
}

【讨论】:

    【解决方案2】:

    您的代码中的“主要”对象是什么? 为什么要使用 setTimeout?

    您需要将 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() {...}
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-31
      相关资源
      最近更新 更多