How to use json data in ListView of React Native

范例一:

myths-Mac:~ myth$ react-native init jason

App.js文件完整的代码如下(使用fetch获取数据的方式):

import React,{Component} from 'React';  
    import {  
    StyleSheet,  
    ActivityIndicator,  
    ListView,  
    Text,  
    View,  
    Alert,  
    Platform,  
    TouchableOpacity} from 'react-native';  
    export default class App  extends Component {  
        constructor(props) {  
          super(props);  
          this.state = {  
            isLoading: true  
          }  
        }  
        GetItem (student_name) {  
            Alert.alert(student_name);  
        }  
        componentDidMount() {  
            fetch('https://reactnativecode.000webhostapp.com/StudentsList.php')  
            .then((response) => response.json())  
            .then((responseJson) => {  
              let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});  
              this.setState({  
                isLoading: false,  
                dataSource: ds.cloneWithRows(responseJson),  
              }, function() {  
                // In this block you can do something with new state.  
              });  
            })  
            .catch((error) => {  
              console.error(error);  
            });  
        }  
      
        ListViewItemSeparator = () => {  
          return (  
            <View  
              style={{  
                height: .5,  
                width: "100%",  
                backgroundColor: "#000",  
              }}  
            />  
          );  
        }  
      
        render() {  
          if (this.state.isLoading) {  
            return (  
              <View style={{flex: 1, paddingTop: 20}}>  
                <ActivityIndicator />  
              </View>  
            );  
          }  
          return (  
            <View style={styles.container}>  
              <ListView  
                dataSource={this.state.dataSource}  
                renderSeparator= {this.ListViewItemSeparator}  
                renderRow={(rowData) =>  
               <View style={{flex:1, flexDirection: 'column'}} >  
                 <TouchableOpacity onPress={this.GetItem.bind(this, rowData.student_name)} >  
                 <Text style={styles.textField} >{'id = ' + rowData.id}</Text>  
                 <Text style={styles.textField} >{'Name = ' + rowData.student_name}</Text>  
                 <Text style={styles.textField} >{'Phone Number = ' + rowData.student_phone_number}</Text>  
                 <Text style={styles.textField} >{'Subject = ' + rowData.student_subject}</Text>  
                 </TouchableOpacity>  
               </View>  
                }  
              />  
            </View>  
          );  
        }  
    }  
      
    const styles = StyleSheet.create({  
    container :{  
    // Setting up View inside content in Vertically center.  
    justifyContent: 'center',  
    flex:1,  
    paddingTop: (Platform.OS === 'ios') ? 20 : 0,  
    backgroundColor: '#00BCD4',  
    padding: 5,  
    },  
    textField: {  
     textAlignVertical:'center',  
     padding:10,  
     fontSize: 20,  
     color: '#fff',  
    }  
    });  

App.js文件完整的代码如下(使用axios获取数据的方式):

$ cd /Users/myth/jason && yarn add axios

import React,{Component} from 'React';
import {
StyleSheet,
ActivityIndicator,
ListView,
Text,
View,
Alert,
Platform,
TouchableOpacity} from 'react-native';
import axios from 'axios';
export default class App  extends Component {
    constructor(props) {
      super(props);
      this.state = {
        isLoading: true
      }
    }
    GetItem (student_name) {
        Alert.alert(student_name);
    }
    componentDidMount() {
      axios.get('https://reactnativecode.000webhostapp.com/StudentsList.php')
        .then((response) => {
             let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
             this.setState({
               isLoading: false,
               dataSource: ds.cloneWithRows(response.data),
             });
        }).catch(function (error) {
            console.log(error);
        });
      }

    ListViewItemSeparator = () => {
      return (
        <View
          style={{
            height: .5,
            width: "100%",
            backgroundColor: "#000",
          }}
        />
      );
    }

    render() {
      if (this.state.isLoading) {
        return (
          <View style={{flex: 1, paddingTop: 20}}>
            <ActivityIndicator />
          </View>
        );
      }
      return (
        <View style={styles.container}>
          <ListView
            dataSource={this.state.dataSource}
            renderSeparator= {this.ListViewItemSeparator}
            renderRow={(rowData) =>
           <View style={{flex:1, flexDirection: 'column'}} >
             <TouchableOpacity onPress={this.GetItem.bind(this, rowData.student_name)} >
             <Text style={styles.textField} >{'id = ' + rowData.id}</Text>
             <Text style={styles.textField} >{'Name = ' + rowData.student_name}</Text>
             <Text style={styles.textField} >{'Phone Number = ' + rowData.student_phone_number}</Text>
             <Text style={styles.textField} >{'Subject = ' + rowData.student_subject}</Text>
             </TouchableOpacity>
           </View>
            }
          />
        </View>
      );
    }
}

const styles = StyleSheet.create({
container :{
// Setting up View inside content in Vertically center.
justifyContent: 'center',
flex:1,
paddingTop: (Platform.OS === 'ios') ? 20 : 0,
backgroundColor: '#00BCD4',
padding: 5,
},
textField: {
 textAlignVertical:'center',
 padding:10,
 fontSize: 20,
 color: '#fff',
}
});    


不管上面那种代码的写法 android 手机模拟器都能正常读取远程链接

https://reactnativecode.000webhostapp.com/StudentsList.php

返回的数据:

[{"id":"1","student_name":"Rohit","student_phone_number":"1234567890","student_subject":"C++"},{"id":"2","student_name":"Mukesh","student_phone_number":"0987654321","student_subject":"PHP"},{"id":"4","student_name":"Rita","student_phone_number":"1234567890","student_subject":"JAVA"},{"id":"5","student_name":"Nikita","student_phone_number":"0987654321","student_subject":"Maths"},{"id":"6","student_name":"Sonal","student_phone_number":"1234567890","student_subject":"English"},{"id":"7","student_name":"Pankaj","student_phone_number":"1029384756","student_subject":"HTML"},{"id":"8","student_name":"Nighat","student_phone_number":"0987654321","student_subject":"Android"},{"id":"9","student_name":"Amit","student_phone_number":"0987654321","student_subject":"Operating System"},{"id":"10","student_name":"Dipak","student_phone_number":"1234567890","student_subject":"Hindi"},{"id":"11","student_name":"Ravish","student_phone_number":"0987654321","student_subject":"DBMS"}]

但是苹果手机必须修改app项目jason中的Info.plist文件中的内容才允许使用https协议去请求访问数据,下面是一份完整的没有任何问题Info.plist配置文件(用开发工具Android Studio直接去修改Info.plist文件很方便,不推荐用XCode编辑工具去修改Info.plist,因为编辑此文件太麻烦啦):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>CFBundleDevelopmentRegion</key>
	<string>en</string>
	<key>CFBundleDisplayName</key>
	<string>jason</string>
	<key>CFBundleExecutable</key>
	<string>$(EXECUTABLE_NAME)</string>
	<key>CFBundleIdentifier</key>
	<string>org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)</string>
	<key>CFBundleInfoDictionaryVersion</key>
	<string>6.0</string>
	<key>CFBundleName</key>
	<string>$(PRODUCT_NAME)</string>
	<key>CFBundlePackageType</key>
	<string>APPL</string>
	<key>CFBundleShortVersionString</key>
	<string>1.0</string>
	<key>CFBundleSignature</key>
	<string>????</string>
	<key>CFBundleVersion</key>
	<string>1</string>
	<key>LSRequiresIPhoneOS</key>
	<true/>
	<key>UILaunchStoryboardName</key>
	<string>LaunchScreen</string>
	<key>UIRequiredDeviceCapabilities</key>
	<array>
		<string>armv7</string>
	</array>
	<key>UISupportedInterfaceOrientations</key>
	<array>
		<string>UIInterfaceOrientationPortrait</string>
		<string>UIInterfaceOrientationLandscapeLeft</string>
		<string>UIInterfaceOrientationLandscapeRight</string>
	</array>
	<key>UIViewControllerBasedStatusBarAppearance</key>
	<false/>
	<key>NSLocationWhenInUseUsageDescription</key>
	<string></string>
	<key>NSAppTransportSecurity</key>
	<!--See http://ste.vn/2015/06/10/configuring-app-transport-security-ios-9-osx-10-11/ -->
	<dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
		<key>NSExceptionDomains</key>
		<dict>
			<key>localhost</key>
            <dict>
                <key>NSExceptionAllowsInsecureHTTPLoads</key>
                <true/>
                <key>NSExceptionMinimumTLSVersion</key>
                <string>TLSv1.1</string>
                <key>NSIncludesSubdomains</key>
                <true/>
            </dict>
		</dict>
	</dict>
</dict>
</plist>

本范例中请求的远程链接地址https协议和http协议均支持,顺便看看它的证书信息:


我们在使用fetch或者axios访问网络链接时,常常会首先检查用手机模拟器内集成的浏览器是否能访问网络链接地址,当浏览器直接返回数据时,说明手机网络正常,请求访问的域名也能正常解析(IP到域名映射关系正常,尤其是自己定义的域名,手机端hosts文件里必须配置IP到域名的映射关系),我们检查手机网络正常,直接用手机里的浏览器检查,正常情况下的截图如下:



To run your app on iOS:

   cd /Users/myth/jason
   react-native run-ios
   - or -
   Open ios/jason.xcodeproj in Xcode
   Hit the Run button
To run your app on Android:
   cd /Users/myth/jason
   Have an Android emulator running (quickest way to get started), or a device connected
   react-native run-android
myths-Mac:~ myth$ cd jason
myths-Mac:doo myth$ Open ios/jason.xcodeproj

cd /Users/myth/jason && react-native run-ios

cd /Users/myth/jason && react-native run-android   #必须首先启动安卓模拟器才可以执行此条指令

jason项目范例在安卓和苹果模拟器中运行的效果截图如下:


范例二:

https://jsonplaceholder.typicode.com/users 该链接返回的数据如下:

[
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "[email protected]",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
      "name": "Romaguera-Crona",
      "catchPhrase": "Multi-layered client-server neural-net",
      "bs": "harness real-time e-markets"
    }
  },
  {
    "id": 2,
    "name": "Ervin Howell",
    "username": "Antonette",
    "email": "[email protected]",
    "address": {
      "street": "Victor Plains",
      "suite": "Suite 879",
      "city": "Wisokyburgh",
      "zipcode": "90566-7771",
      "geo": {
        "lat": "-43.9509",
        "lng": "-34.4618"
      }
    },
    "phone": "010-692-6593 x09125",
    "website": "anastasia.net",
    "company": {
      "name": "Deckow-Crist",
      "catchPhrase": "Proactive didactic contingency",
      "bs": "synergize scalable supply-chains"
    }
  },
  {
    "id": 3,
    "name": "Clementine Bauch",
    "username": "Samantha",
    "email": "[email protected]",
    "address": {
      "street": "Douglas Extension",
      "suite": "Suite 847",
      "city": "McKenziehaven",
      "zipcode": "59590-4157",
      "geo": {
        "lat": "-68.6102",
        "lng": "-47.0653"
      }
    },
    "phone": "1-463-123-4447",
    "website": "ramiro.info",
    "company": {
      "name": "Romaguera-Jacobson",
      "catchPhrase": "Face to face bifurcated interface",
      "bs": "e-enable strategic applications"
    }
  },
  {
    "id": 4,
    "name": "Patricia Lebsack",
    "username": "Karianne",
    "email": "[email protected]",
    "address": {
      "street": "Hoeger Mall",
      "suite": "Apt. 692",
      "city": "South Elvis",
      "zipcode": "53919-4257",
      "geo": {
        "lat": "29.4572",
        "lng": "-164.2990"
      }
    },
    "phone": "493-170-9623 x156",
    "website": "kale.biz",
    "company": {
      "name": "Robel-Corkery",
      "catchPhrase": "Multi-tiered zero tolerance productivity",
      "bs": "transition cutting-edge web services"
    }
  },
  {
    "id": 5,
    "name": "Chelsey Dietrich",
    "username": "Kamren",
    "email": "[email protected]",
    "address": {
      "street": "Skiles Walks",
      "suite": "Suite 351",
      "city": "Roscoeview",
      "zipcode": "33263",
      "geo": {
        "lat": "-31.8129",
        "lng": "62.5342"
      }
    },
    "phone": "(254)954-1289",
    "website": "demarco.info",
    "company": {
      "name": "Keebler LLC",
      "catchPhrase": "User-centric fault-tolerant solution",
      "bs": "revolutionize end-to-end systems"
    }
  },
  {
    "id": 6,
    "name": "Mrs. Dennis Schulist",
    "username": "Leopoldo_Corkery",
    "email": "[email protected]",
    "address": {
      "street": "Norberto Crossing",
      "suite": "Apt. 950",
      "city": "South Christy",
      "zipcode": "23505-1337",
      "geo": {
        "lat": "-71.4197",
        "lng": "71.7478"
      }
    },
    "phone": "1-477-935-8478 x6430",
    "website": "ola.org",
    "company": {
      "name": "Considine-Lockman",
      "catchPhrase": "Synchronised bottom-line interface",
      "bs": "e-enable innovative applications"
    }
  },
  {
    "id": 7,
    "name": "Kurtis Weissnat",
    "username": "Elwyn.Skiles",
    "email": "[email protected]",
    "address": {
      "street": "Rex Trail",
      "suite": "Suite 280",
      "city": "Howemouth",
      "zipcode": "58804-1099",
      "geo": {
        "lat": "24.8918",
        "lng": "21.8984"
      }
    },
    "phone": "210.067.6132",
    "website": "elvis.io",
    "company": {
      "name": "Johns Group",
      "catchPhrase": "Configurable multimedia task-force",
      "bs": "generate enterprise e-tailers"
    }
  },
  {
    "id": 8,
    "name": "Nicholas Runolfsdottir V",
    "username": "Maxime_Nienow",
    "email": "[email protected]",
    "address": {
      "street": "Ellsworth Summit",
      "suite": "Suite 729",
      "city": "Aliyaview",
      "zipcode": "45169",
      "geo": {
        "lat": "-14.3990",
        "lng": "-120.7677"
      }
    },
    "phone": "586.493.6943 x140",
    "website": "jacynthe.com",
    "company": {
      "name": "Abernathy Group",
      "catchPhrase": "Implemented secondary concept",
      "bs": "e-enable extensible e-tailers"
    }
  },
  {
    "id": 9,
    "name": "Glenna Reichert",
    "username": "Delphine",
    "email": "[email protected]",
    "address": {
      "street": "Dayna Park",
      "suite": "Suite 449",
      "city": "Bartholomebury",
      "zipcode": "76495-3109",
      "geo": {
        "lat": "24.6463",
        "lng": "-168.8889"
      }
    },
    "phone": "(775)976-6794 x41206",
    "website": "conrad.com",
    "company": {
      "name": "Yost and Sons",
      "catchPhrase": "Switchable contextually-based project",
      "bs": "aggregate real-time technologies"
    }
  },
  {
    "id": 10,
    "name": "Clementina DuBuque",
    "username": "Moriah.Stanton",
    "email": "[email protected]",
    "address": {
      "street": "Kattie Turnpike",
      "suite": "Suite 198",
      "city": "Lebsackbury",
      "zipcode": "31428-2261",
      "geo": {
        "lat": "-38.2386",
        "lng": "57.2232"
      }
    },
    "phone": "024-648-3804",
    "website": "ambrose.net",
    "company": {
      "name": "Hoeger LLC",
      "catchPhrase": "Centralized empowering task-force",
      "bs": "target end-to-end models"
    }
  }
]

App.js文件完整的代码如下

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

export default class App extends Component {
    constructor(){
        super();
        const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        this.state = {
            userDataSource: ds,
        };
    }
    componentDidMount(){
        this.fetchUsers();
    }
    fetchUsers(){
        fetch('https://jsonplaceholder.typicode.com/users')
        .then((respnose) => respnose.json())
        .then((data) => {
            this.setState({
                userDataSource: this.state.userDataSource.cloneWithRows(data)
            });
        });
    }
    renderRow(user,sectionId,rowId,highlightRow){
        return (
            <View style={styles.row}>
                <Text style={styles.rowText}>{user.name}</Text>
                <Text style={styles.rowText}>{user.phone}</Text>
            </View>
        );
    }
    render() {
        return (
            <ListView
                dataSource={this.state.userDataSource}
                renderRow={this.renderRow.bind(this)}
            />
        );
    }
}

const styles = StyleSheet.create({
    row: {
        flexDirection: 'row',
        justifyContent: 'center',
        padding: 10,
        backgroundColor: 'rgba(195,195,195,1.0)',
        marginBottom: 3,
    },
    rowText: {
        flex: 1,
    },
})
本范例在安卓和苹果模拟器中运行的效果截图如下:

猜你喜欢

转载自blog.csdn.net/zhengzizhi/article/details/79904248