React-native FlatList的基本用法

官網(wǎng)FlatList解讀
FlatList被稱為升級版的ListView,在大量數(shù)據(jù)渲染的時(shí)候,不會造成內(nèi)存飆升,進(jìn)而具有很好的性能體驗(yàn),目前還在試水階段,網(wǎng)絡(luò)上沒有多少“最佳實(shí)踐”,RN開發(fā)是一個(gè)不斷挖坑填坑的旅途,在這一片泥濘的路上,希望通過一點(diǎn)總結(jié)和嘗試會變成一塊塊墊腳石,給這條路添加一點(diǎn)點(diǎn)平坦,為跨平臺生態(tài)圈增加些許色彩!

1.引入FlatList組件

import {
  AppRegistry,
  StyleSheet,
  Text,
  View
  ActivityIndicator, 
  FlatList, 
  ScrollView
} from 'react-native';

2.模擬網(wǎng)絡(luò)數(shù)據(jù)

const REQUEST_URL = 'https://api.github.com/search/repositories?q=ALL&sort=stars';

3.設(shè)置狀態(tài)機(jī)state

constructor(props){
    super(props);
    this.state = {
      isLoading: true,
      //網(wǎng)絡(luò)請求狀態(tài)
      error: false,
      errorInfo: "",
      dataArray: [],
    }

  }

4.請求網(wǎng)絡(luò)數(shù)據(jù)方法

_fetchData(){
    fetch(REQUEST_URL)
      .then((response) => response.json())
      .then((data) => {
        let datalist = data.items;
        let dataBlog = [];
        let i = 0;

        datalist.map((item) => {
          dataBlog.push({
            key:i,
            value:item
          })
          i++;
        })

        this.setState({
          dataArray:dataBlog,
          isLoading:false,
        })

        datalist = null;
        dataBlog = null;
      })
      .catch((err) => {
        this.setState({
          error:true,
          errorInfo:err
        })
      })
      .done()
  }

注意:

如果將dataArray直接設(shè)置為data.items,運(yùn)行時(shí)會報(bào)錯(cuò):VirtualizedList: missing keys for items, make sure to specify a key property on each item or provide a custom keyExtractor.
因此,要將dataArray設(shè)置為dataBlog的格式。

5.渲染每一個(gè)item的方法

_renderItemView(item){
    console.log(item.index)
    // VirtualizedList: missing keys for items, 
    // make sure to specify a key property on each item or provide a custom keyExtractor.
    // item數(shù)據(jù)結(jié)構(gòu)中必須要有個(gè)key
    return (
      <View style={styles.cellStyle}>
          <Text>{item.item.value.description}</Text>
      </View>
    )
  }

注意:要想拿到數(shù)組中的數(shù)據(jù),必須指定item.item.value,不信可以打印出item試試,觀察他的數(shù)據(jù)結(jié)構(gòu)。

6.數(shù)據(jù)沒有加載出來的時(shí)候(菊花圖)

renderLoadingView(){
    return (
       <View style={styles.container}>
          <ActivityIndicator
              animating={true}
              style={{height: 80}}
              color='red'
              size="large"
          />
      </View>
    )
  }

6.加載失敗的時(shí)候

//加載失敗view
  renderErrorView(error) {
      return (
          <View style={styles.container}>
              <Text>
                  Fail: {error}
              </Text>
          </View>
      );
  }

7.完整的代碼:

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image,
  TouchableHighlight,
  TouchableOpacity,
  ActivityIndicator, 
  FlatList, 
  ScrollView,
  RefreshControl
} from 'react-native';

// 頂部標(biāo)題View
import NavigationBar from '../common/NavigationBar';

const REQUEST_URL = 'https://api.github.com/search/repositories?q=ALL&sort=stars';

export default class MusicPage extends Component {
  constructor(props){
    super(props);
    this.state = {
      isLoading: true,
      //網(wǎng)絡(luò)請求狀態(tài)
      error: false,
      errorInfo: "",
      dataArray: [],
    }

  }

  componentDidMount() {
    this._fetchData(); 
  }

  _fetchData(){
    fetch(REQUEST_URL)
      .then((response) => response.json())
      .then((data) => {
        let datalist = data.items;
        let dataBlog = [];
        let i = 0;

        datalist.map((item) => {
          dataBlog.push({
            key:i,
            value:item
          })
          i++;
        })

        this.setState({
          dataArray:dataBlog,
          isLoading:false,
        })

        datalist = null;
        dataBlog = null;
      })
      .catch((err) => {
        this.setState({
          error:true,
          errorInfo:err
        })
      })
      .done()
  }

  _renderItemView(item){
    console.log(item.index)
    // VirtualizedList: missing keys for items, 
    // make sure to specify a key property on each item or provide a custom keyExtractor.
    // item數(shù)據(jù)結(jié)構(gòu)中必須要有個(gè)key
    return (
      <View style={styles.cellStyle}>
          <Text>{item.item.value.description}</Text>
      </View>
    )
  }

  renderLoadingView(){
    return (
       <View style={styles.container}>
          <ActivityIndicator
              animating={true}
              style={{height: 80}}
              color='red'
              size="large"
          />
      </View>
    )
  }

  //加載失敗view
  renderErrorView(error) {
      return (
          <View style={styles.container}>
              <Text>
                  Fail: {error}
              </Text>
          </View>
      );
  }

  _renderFlatlist(){

    //第一次加載等待的view
    if (this.state.isLoading && !this.state.error) {
        return this.renderLoadingView();
    } else if (this.state.error) {
        //請求失敗view
        return this.renderErrorView(this.state.errorInfo);
    }

    return (
      <ScrollView>
        <FlatList 
            data={this.state.dataArray}
            renderItem={(item)=>this._renderItemView(item)}
        />
      </ScrollView>
    )    
  }
  
  render() {

    return (
      <View style={styles.container}>
        <NavigationBar
            title='FlatList'
            />
        {/* 這里渲染選項(xiàng)卡UI */}
        {this._renderFlatlist()}
      </View>
    )
    
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  cellStyle:{
    flex: 1,
    backgroundColor: 'white',
    padding: 10,
    paddingVertical:20,
    marginLeft: 5,
    marginRight: 5,
    marginVertical: 3,
    borderColor: '#dddddd',
    borderStyle: null,
    borderWidth: 0.5,
    borderRadius: 2,
    shadowColor: 'gray',    // 設(shè)置陰影
    shadowOffset: {width:0.5, height: 0.5},  
    shadowOpacity: 0.4,   // 透明度
    shadowRadius: 1,
    elevation:2   //   高度,設(shè)置Z軸,可以產(chǎn)生立體效果
  }
});


8.效果圖如下:

效果圖smartisanT2
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容