【React Native开发】

来源:互联网 发布:网络微信图片发不出去 编辑:程序博客网 时间:2024/05/21 08:57

React Native 使用fetch进行网络请求

1.介绍

Fetch 请求网络的方式和web请求网络的方式是一致的,可用于满足开发者访问网络的需求

2.get请求

2-1 在构造方法中初始化数据

constructor(props){    super(props)    this.state = {        dataSource:new ListView.DataSource({            rowHasChanged:((row1,row2) => (row1 !== row2))        }),        load:false    }}2-2 在componentDidMount()方法中请求网络,获得数据源
componentDidMount()页面加载完成后执行
getData(){    fetch('http://gank.io/api/data/%E7%A6%8F%E5%88%A9/10/2',{        method:'GET',//get请求    })        .then((response) => response.json())//获取数据        .then((responseText) => {//处理数据            this.setState({//刷新界面                load:true,                dataSource:this.state.dataSource.cloneWithRows(responseText.results)            })        })        .catch((error) => {//获取数据错误时执行            console.warn(error)        }).done()}Json 数据2-3 渲染界面
render(){    if (!this.state.load){        return this.renderLoading()    }    return this.renderListView(this.state.dataSource)    }//页面加载时执行 
renderLoading(){    return (        <View style={styles.load}>            <Text>正在加载中...</Text>        </View>    )}//数据加载完毕,获取数据时执行 
renderListView(dataSource){    return (        <ListView            dataSource={dataSource}            renderRow={this.renderRow}>                    </ListView>    )}//渲染界面 renderRow(rowData){    return (        <View style={styles.container}>            <Image source={{ uri: rowData.url }}  style={{ width: width, height: height / 2, marginTop: 5 }}></Image>        </View>    )}2-4 样式
const styles = StyleSheet.constructor({    container:{        flex:1,    },    load:{        flex:1,        justifyContent:'center',        alignItems:'center',    },})
2-5 效果:









原创粉丝点击