无法让`fetch()`在React Native中工作

时间:2015-11-07 06:39:25

标签: react-native

知道为什么我不能让fetch()在React Native工作吗?完整代码在RN Play上: https://rnplay.org/apps/L80w2w

这是一个有效的ReactJS小提琴,我正试图在React Native中工作:https://jsfiddle.net/ssorallen/fEsYt/

componentDidMount: function() {
        var _this = this;
        var queryParams = "fn" + Date.now() + '/';
        var queryUrl = "https://www.reddit.com/reddits.json?jsonp=" + queryParams;

        fetch(queryUrl)
          .then(response => response.json())
          .then(responseData => this._handleResponse(responseData.data.children))
          .catch(error => this.setState({
            isLoading: false,
            errorMessage: 'Something bad happened - loading navigationItems: \n' + error
          }));
    },

    _handleResponse(results) {
        this.setState({ isLoading: false });

        if (results.length > 0) {
            this.setState({
                navigationItems: results
            });
        } else {
          this.setState({ errorMessage: "Can't find JSON." });
        }
    },    

2 个答案:

答案 0 :(得分:4)

您正在尝试使用JSONP技术调用Reddit,这是不必要的,因为React Native不像浏览器那样强加Same-Origin安全策略。

如果您从网址中删除?jsonp=" + queryParams参数,则请求应该有效。

答案 1 :(得分:0)

    completed = (id) => {
        var details = {
            'id': id,

        };

        var formBody = [];
        for (var property in details) {
            var encodedKey = encodeURIComponent(property);
            var encodedValue = encodeURIComponent(details[property]);
            formBody.push(encodedKey + "=" + encodedValue);
        }
        formBody = formBody.join("&");

        fetch(markcompleted, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: formBody
        })
            .then((response) => response.json())
            .then((responseJson) => {
                console.log(responseJson, 'res JSON');
                if (responseJson.status == "success") {
                    console.log(this.state);
                    alert("your todolist is completed!!");
                }
            })
            .catch((error) => {
                console.error(error);
            });
    };

#change post into get