React Native First demo (2) network fetch data and ListView

Source: Internet
Author: User
Tags json


Continue on React native first demo (1) 1, network get real data 1.1 define variables



Place the following URL variable at the top of the index.ios.js, which is usually placed under imports.


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

 
1.2 Initialization 


Add some initialization, this.state.movies = = = NULL, so we can tell if the movies data is loaded.


Constructor (props) {
    super (props);
    This.state = {
      movies:null,
    };
  }
1.3 fetchdata ()


Gets the data when the component is loaded. When the data is returned, the callback sets the state's movies to the movie Information data list.


Componentdidmount () {
    this.fetchdata ();
  }
Fetchdata () {
    fetch (request_url)
      . Then ((response) = Response.json ())
      . Then ((responsedata) = {
        this.setstate ({
          movies:responseData.movies,
        });
      })
      . Done ();
  }
1.4 Loading view and rendering of the data obtained


After getting the data returned, the setting State,render is called again, at which point this.state.movies is not NULL, calling Rendermovie to set and display the data to the interface.


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 Display Network Data


Why use a ListView without scrollview or displaying the data directly? Because the ListView only renders the data in the display part, the performance is good. 2.1 Adding a ListView module


Import React, {
  Component,
} from ' React ';
Import {
  appregistry,
  Image,
  ListView,
  StyleSheet,
  Text,
  View,
} from ' React-native ';
2.2 Modifying the constructor and render


Add DataSource variable and loaded, easy to use, avoid this.state.movies storage two times. Rowhaschanged is a method that the react component record state is updated, and if it is equal, the state change page is not updated and does not equal if the state change page is updated immediately.


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& Add RowStyle to the ListView
Fetchdata () {
    fetch (request_url)
      . Then ((response) = Response.json ())
      . Then ((responsedata) = {
        this.setstate ({
          dataSource:this.state.dataSource.cloneWithRows (responsedata.movies),
          loaded: True,
        });
      })
      . Done ();
  }

Add the following to the Stlyes
 listView: {
    paddingtop:20,
    backgroundcolor: ' #F5FCFF ',
  },
2.4 Full Code
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);


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


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.