React Native第一个Demo(2)网络获取数据和ListView

继续上一篇React Native第一个Demo(1)

1、网络获取真实数据

1.1定义变量

把下面url变量放在index.ios.js顶部,通常是要放在 imports下面。

var REQUEST_URL = 'https://raw.githubusercontent.com/facebook/react-native/master/docs/MoviesExample.json';

1.2初始化

添加一些初始化,this.state.movies === null,这样我们可以判断movies数据是否被加载了。

constructor(props) {
    super(props);
    this.state = {
      movies: null,
    };
  }

1.3 fetchData()

在组件加载时,获取数据。数据返回时,回调设置state的movies为电影信息数据列表。

componentDidMount() {
    this.fetchData();
  }
fetchData() {
    fetch(REQUEST_URL)
      .then((response) => response.json())
      .then((responseData) => {
        this.setState({
          movies: responseData.movies,
        });
      })
      .done();
  }

1.4 loading的视图和渲染获取的数据

获取数据返回后,设置state,render被再次调用,这时this.state.movies不为null,调用renderMovie设置和展示数据到界面上。

 render() {
    if (!this.state.movies) {
      return this.renderLoadingView();
    }

    var movie = this.state.movies[0];
    return this.renderMovie(movie);
  }
  renderLoadingView() {
    return (
      <View style={styles.container}>
        <Text>
          Loading movies...
        </Text>
      </View>
    );
  }

  renderMovie(movie) {
    return (
      <View style={styles.container}>
        <Image
          source={{uri: movie.posters.thumbnail}}
          style={styles.thumbnail}
        />
        <View style={styles.rightContainer}>
          <Text style={styles.title}>{movie.title}</Text>
          <Text style={styles.year}>{movie.year}</Text>
        </View>
      </View>
    );
  }

2、ListView展示网络数据

为什么要用ListView不用scrollview或把数据直接显示出来呢? 因为ListView只渲染展示部分的数据,效率高性能好。

2.1 增加ListView模块

import React, {
  Component,
} from 'react';
import {
  AppRegistry,
  Image,
  ListView,
  StyleSheet,
  Text,
  View,
} from 'react-native';

2.2 修改构造器和render

增加dataSource变量和loaded,方便使用,避免this.state.movies两次存储。rowHasChanged是 react组件纪录 state 是否更新的一个方法, 如果是等于,state变化 页面不更新 , 不等于,如果state变化 页面立即更新。

constructor(props) {
    super(props);
    this.state = {
      dataSource: new ListView.DataSource({
        rowHasChanged: (row1, row2) => row1 !== row2,
      }),
      loaded: false,
    };
  }
 render() {
    if (!this.state.loaded) {
      return this.renderLoadingView();
    }

    return (
      <ListView
        dataSource={this.state.dataSource}
        renderRow={this.renderMovie}
        style={styles.listView}
      />
    );
  }

2.3 fetchData&增加listview的rowstyle

 fetchData() {
    fetch(REQUEST_URL)
      .then((response) => response.json())
      .then((responseData) => {
        this.setState({
          dataSource: this.state.dataSource.cloneWithRows(responseData.movies),
          loaded: true,
        });
      })
      .done();
  }

//下面增加到stlyeslistView: {
    paddingTop: 20,
    backgroundColor: '#F5FCFF',
  },

2.4 完整代码


import React, {
    Component,
} from 'react';

import {
     AppRegistry,
     Image,
     StyleSheet,
     Text,
     View,
     ListView,
 } from 'react-native';



 var REQUEST_URL = 'https://raw.githubusercontent.com/facebook/react-native/master/docs/MoviesExample.json';


 class DemoProject extends Component
 {
     constructor(props) {
         super(props);
         this.state = {
             dataSource: new ListView.DataSource({
                 rowHasChanged: (row1, row2) => row1 !== row2,
             }),
             loaded: false,
         };
     }

     componentDidMount(){
         this.fetchData();
     }

     fetchData() {
         fetch(REQUEST_URL)
             .then((response) => response.json())
             .then((responseData) => {
                 this.setState({
                     dataSource: this.state.dataSource.cloneWithRows(responseData.movies),
                     loaded: true,
                 });
             })
             .done();
     }

     render() {
         if (!this.state.loaded) {
             return this.renderLoadingView();
         }

         return (
             <ListView
                 dataSource={this.state.dataSource}
                 renderRow={this.renderMovie}
                 style={styles.listView}
             />
         );
     }

     renderLoadingView()
     {
         return (<View style={styles.container} >
                 <Text>Loading movies......</Text>
             </View>

         );
     }

     renderMovie(movie) {
         return (
             <View style={styles.container}>
                 <Image
                     source={{uri: movie.posters.thumbnail}}
                     style={styles.thumbnail}
                 />
                 <View style={styles.rightContainer}>
                     <Text style={styles.title}>{movie.title}</Text>
                     <Text style={styles.year}>{movie.year}</Text>
                 </View>
             </View>
         );
     }


 };


 var styles = StyleSheet.create({
     container: {
         flex: 1,
         flexDirection: 'row',
         justifyContent: 'center',
         alignItems: 'center',
         backgroundColor: '#F5FCFF',
     },
     rightContainer: {
         flex: 1,
     },
     title: {
         fontSize: 20,
         marginBottom: 8,
         textAlign: 'center',
     },
     year: {
         textAlign: 'center',
     },
     thumbnail: {
         width: 53,
         height: 81,
     },
     listView: {
         paddingTop: 20,
         backgroundColor: '#F5FCFF',
     },
 });
 AppRegistry.registerComponent('DemoProject', () => DemoProject);

参考:http://facebook.github.io/react-native/docs/tutorial.html

猜你喜欢

转载自blog.csdn.net/totogo2010/article/details/51593833