ReactNative学习第七天 项目fetch+ListView

来源:互联网 发布:javascript json rpc 编辑:程序博客网 时间:2024/05/22 01:56

昨天我搭了一个壳,里面什么数据都没有

今天我要做数据请求+列表展示,当时是最简单的例子,毕竟我是个初学者


请求数据用 fetch


fetch('http://facebook.github.io/react-native/movies.json')


例子的部分代码:


// 初始化模拟数据

constructor(props) {

    super(props);

    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});

    this.state = {

    dataSource: ds.cloneWithRows(["row1"]),

    title: "row1"

    };

    this.getdataFromApiAsync(); //请求数据方法

}


//请求数据

getdataFromApiAsync() {

    return fetch('http://facebook.github.io/react-native/movies.json')

    .then((response) => response.json())

    .then((responseJson) => {

        let jsondata = responseJson.movies;

        const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});

        this.setState({dataSource: ds.cloneWithRows(jsondata)});

        this.setState({title:jsondata.title});

    })

    .catch((error) => {

        console.error(error);

    });

}


//请求到的数据用ListView展示

render() {

    return (

        <View style={{flex:1,backgroundColor:'white'}}>

            <ListView style={{backgroundColor:'yellow'}}

            dataSource={this.state.dataSource}

            renderRow={(rowData) => <CELL title={rowData.title} detailTitle={rowData.releaseYear}></CELL>}

            />

        </View>

            );

}


//CELL的代码

class CELL extends React.Component{

    

    constructor(props){

        super(props);

        this.state = { detailTitle:'aaaa'};

    }

    render(){

        return(

           <View style={{flex:1}}>

               <Text style={styles.title}>

                   {this.props.detailTitle}

               </Text>

               <View style={styles.lineStyle}>

               </View>

           </View>

               );

    }

}


//样式

const styles = StyleSheet.create({

    container: {

        flexDirection: 'row',

        paddingLeft: 10,

        paddingRight: 10,

        paddingTop: 0,

        height: 68,

        backgroundColor: '#d74047',

        alignItems: 'center'

    },

    tableView: {

        paddingLeft: 0,

        paddingRight: 0,

        paddingTop: 0,

        paddingBottom:0,

    },

    title:{

        textAlign:'center',

        color:'grey',

        fontWeight:'bold',

        fontSize:28,

        flex: 1,//自动填充

    },

    lineStyle:{

        paddingLeft: 0,

        paddingRight: 0,

        backgroundColor: 'black',

        height:1,

    }

});


运行看看,效果如下,丑的很特别。问我为什么设计的这么丑,只是我有些点还没搞清楚,页面布局的知识还是不够,抽个时间好好整理下布局这块。明天进行点击跳转了,今天没时间了哈。。。