ReactNative学习实例(三) 使用fetch获取网络数据

实例来自http://blog.csdn.net/u014360817/article/details/52447516


RN自带了一个非常优雅的网络操作库fetch,下面的这个例子从gankio的接口拿到了美女图片的url然后通过state 传给列表组件,列表里返回图片组件显示图片。网络数据获取方法写在componentDidMount中,这个方法是组件生命周期中需要调用的一个方法。

class AwesomeProject extends Component {// 初始化模拟数据


    constructor(props) {
        super(props);

        const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => {r1 !== r2}});
        this.state = {
            dataSource: ds,
            load:false,
            text:''
        };
    }

    //耗时操作放在这里面
    componentDidMount(){
        this.getNet();
    }

    getNet(){
        fetch('http://gank.io/api/search/query/listview/category/福利/count/10/page/1')//请求地址
            .then((response) => response.json())//取数据
            .then((responseText) => {//处理数据
                //通过setState()方法重新渲染界面
                this.setState({
                    //改变加载ListView
                    load: true,
                    //设置数据源刷新界面
                    dataSource: this.state.dataSource.cloneWithRows(responseText.results),
                })

            })
            .catch((error) => {
                console.warn(error);
            }).done();
    }

    render() {
        if(this.state.load){
            return (
                
                    
                            
                                
                            }
                        />
                
            );
        } else{
            return(
                
                    loading......
                
            );
        }
    }
}

这里使用的是fetch的一个参数的方法,参数自然就是url,默认请求方式是GET,还有两个参数的方法,第二个参数是一组请求参数。执行fetch后返回一个Promise对象,通过then继续获取数据,这里response.json表示获取json格式的数据,也可以用text获取纯文本的数据。

获取到json后接下来就是解析json,这里的json里面有一个result数组,直接拿出来作为数据源的数据传入即可。


你可能感兴趣的:(ReactNative)