美文网首页
react-native 记录--fetch下回调事件setSt

react-native 记录--fetch下回调事件setSt

作者: KingZd | 来源:发表于2017-03-30 11:27 被阅读0次

最近用node写了个服务器,想在react-native下面调用并赋值。但是发生了一个问题,代码如下网络请求

const baseUrl = "http://127.0.0.1:3000/";
"use strict";

class NetUtil{

    static getHome(path,callback){
        return fetch(baseUrl+path,this._fetchOptions("GET"))
            .then((res) => res.json())
            .then((resJson) =>{
                callback(resJson);
            })
            .catch((error) => {
                console.log(error);
            }).done()
    };

    register(path,data,callback){
        return fetch(baseUrl+path,this._fetchOptions("POST",data))
            .then((res) => res.json())
            .then((resJson) =>{
                callback(resJson);
            })
            .catch((error) => {
                console.log(error);
            }).done()
    }

    //以后继续封装
    static _fetchOptions(method,data){
        let accept,contentType;
        switch (method){
            case 'POST'://表单
                accept = 'application/json';
                contentType = 'application/x-www-form-urlencoded';
                break;
            case 'GET':
                accept = 'application/json';
                contentType = 'charset=UTF-8';
                break;
        }

        var option = {};
        option.method = method;
        option.headers= {
            'Accept':accept,
            'Content-Type':contentType
        };
        if('GET' != method)
            option.body='data'+data;
        //声明http头
        return option;
    }


    _formatResponse(){

    }
}

module.exports = NetUtil;

调用

constructor(props){
        super(props);
        let nDs = new ListView.DataSource({rowHasChanged:(r1,r2)=>r1!==r2});
        this.state = {
            dataSource2:nDs
        };
    }
_nineItem(){
        NetUtil.getHome("users/test",function (res) {
            this.state.setState({
                dataSource2:this.state.dataSource2.cloneWithRows(res.data)
            })
            console.log(res.data);
        })
    }

这样情况下this.state 的this 的作用域是在NetUtil下 无法给数据源赋值,我这里改成了

_nineItem(){
        var state = this;
        var nDs = this.state.dataSource2;
        NetUtil.getHome("users/test",function (res) {
            state.setState({
                dataSource2:nDs.cloneWithRows(res.data)
            })
            console.log(res.data);
        })
    }

这个是我遇到的一个问题。记录下来,然后看看有啥改进的方法

相关文章

网友评论

      本文标题:react-native 记录--fetch下回调事件setSt

      本文链接:https://www.haomeiwen.com/subject/tuvuottx.html