react-native 记录--fetch下回调事件setState赋值时作用域问题

最近用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);
        })
    }

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容