【问题标题】:Fetch API call not working when executed in React-Native在 React-Native 中执行时,Fetch API 调用不起作用
【发布时间】:2016-10-04 01:05:43
【问题描述】:

我正在尝试在 React Native 中进行 fetch API 调用:

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

class AwesomeProject extends Component {
    render() {
        return (    
            <View style={{flex: 1, flexDirection: 'column', justifyContent: 'center', alignItems: 'center'}}>
            <TextInput 
                placeholder="Enter Text to Be Validated"
                style={{height: 65, width: 275, fontSize: 22}} 
                onSubmitEditing={(event) => {
                    var apiKey = "someAPIKey"
                    var encodedAddress = encodeURIComponent(event.nativeEvent.text)
                    fetch("https://maps.googleapis.com/maps/api/geocode/json?address=" + encodedAddress + "&key=" + apiKey)
                        .then(response => response.json())
                        .then(json => {
                            if (json.status === "OK") {
                                console.log(json.results.formatted_address)
                            }
                            else {
                                console.log("Invalid")
                            }
                    })
                        .catch(err => console.err(err))
                }}
               />   
          </View>
    );
}

但是,注册到 onSubmitEditing 的回调仅在 React-Native 之外进行测试时才有效。有人知道解释吗??

谢谢!!

【问题讨论】:

    标签: react-native fetch


    【解决方案1】:

    试试

    if (json.status === "OK") { console.log(json.results[0].formatted_address) }

    我做了一些挖掘,发现返回的 JSON 有一个状态属性和一个结果数组。您可以使用results[0] 访问该结果数组中的第一项。

    【讨论】:

      猜你喜欢
      • 2016-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-27
      • 2022-12-02
      • 2016-08-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多