React-Native征程(1)

個人奮斗記錄,激勵。。。

環境搭配什么的過了,畢竟比較簡單

API:

AsyncStorage,一句話描述:-----異步特征 的鍵值對 存儲系統

直觀印象:app本地數據存儲,用于數據提交前的,匯總以及整理,(不需要所有數據都在服務端處理),異步特性,實現本地數據異步刷新

含有的可用方法:

1.getItem(key:string,callback:(error,result)):根據鍵獲取值,結果在回調函數中

2.setItem (key:string,value:string,callback:(error)):設置鍵值對

3.mergeItem(ket:string,value:string,callback:(error)):合并現有的值和輸入值,

4.removeitem(key:string,callback:(error)):根據鍵移出一項

5.getAllKeys(callback:(error)):獲取所有的鍵,比較常用的方法

6.multiRemove(keys,callback:(errors)):刪除多項,其中keys是字符串數組

7.multiSet(keyValuePairs,callback:(errors)):設置多項,其中keyValuePairs是字符串的二維數組

8.multiMerge(keyValuePairs,callback:(errors)):多個鍵值對合并

10.clear(callbackL:(error)):清除所有的項目

11.multiGet(keys,callback:(errors,result)):獲取多想,其中keys是字符串數組

案例代碼:購物車demo

5D20F5DA-8814-453B-A259-B1B22B261C8F.png
A2E3E91F-444E-42A8-B23F-4739B92BBC37.png

import React, { Component } from 'react';

import {

  AppRegistry,

  StyleSheet,

  Text,

  View,

  Image,

  NavigatorIOS,

  ScrollView,

  AsyncStorage,

  TouchableOpacity,

} from 'react-native';

var Model = [
  {
    id: '1',
    title: '佳沛新西蘭進口獼猴桃',
    desc: '12個裝',
    price: 99,
    url: 'http://vczero.github.io/ctrip/guo_1.jpg'
  },
  {
    id:'2',
    title: '墨西哥進口牛油果',
    desc: '6個裝',
    price: 59,
    url: 'http://vczero.github.io/ctrip/guo_2.jpg'
  },
  {
    id:'3',
    title: '美國加州進口車厘子',
    desc: '1000g',
    price: 91.5,
    url: 'http://vczero.github.io/ctrip/guo_3.jpg'
  },
  {
    id:'4',
    title: '新疆特產西梅',
    desc: '1000g',
    price: 69,
    url: 'http://vczero.github.io/ctrip/guo_4.jpg'
  },
  {
    id:'5',
    title: '陜西大荔冬棗',
    desc: '2000g',
    price: 59.9,
    url: 'http://vczero.github.io/ctrip/guo_5.jpg'
  },
  {
    id:'6',
    title: '南非紅心西柚',
    desc: '2500g',
    price: 29.9,
    url: 'http://vczero.github.io/ctrip/guo_6.jpg'
  }
];
//一般先創建基礎組件,這里是item組件,包含若干要素,數據將從父節點傳遞而來,
//this.props.是從父節點傳來的值,只讀不可修改,只能在父節點修改
var Item = React.createClass({
  render: function(){
    return(
      <View style={styles.item}>
        <TouchableOpacity onPress={this.props.press}>
          <Image
              resizeMode="contain"
              style={styles.img}
              source={{uri:this.props.url}}>
            <Text numberOfLines={1} style={styles.item_text}>{this.props.title}</Text>
          </Image>
        </TouchableOpacity>
      </View>
    );
  }
});
//重要的列表組件,將item組件作為基本元素,按照逢單裝填一排的樣式,加載item,
var List = React.createClass({
  getInitialState: function(){//getInitialState函數作為結構體初始化操作
    return{
      count:0
    };
  },
  componentDidMount: function(){//組件加載函數,
    var _that = this;
    AsyncStorage.getAllKeys(function(err, keys){//獲取所有鍵,如果出錯退出下面的邏輯,錯誤處理函數沒有完善
      if(err){
        //TODO:存儲取數據出錯
      }
      //將存儲的商品條數反應到按鈕上
      _that.setState({
        count: keys.length
      });
    });
  },
  render: function() {
    var list = [];
    for(var i in Model){
      if(i % 2 === 0){//數組從0開始,每行開始的鍵為0,2,4,6.....
        var row = (//這里需要說明的是 key={i},官網有解釋,跟節點只有一個,
//因此每個子節點需要有自己的id號,否則這里會出現一個警告??
          <View key={i} style={styles.row}>
            <Item
              url={Model[i].url}
              title={Model[i].title}
              press={this.press.bind(this, Model[i])}></Item>
            <Item
              url={Model[parseInt(i)+1].url}
              title={Model[parseInt(i)+1].title}
              press={this.press.bind(this, Model[parseInt(i)+1])}></Item>
          </View>);
        list.push(row);//將每組(一對)item,壓棧row中,
      }
    }

    var count = this.state.count;
    var str = null;
    if(count){
      str = ',共'+ count + '件商品';
    }
    return (
      <ScrollView style={{marginTop:10}}>
        {list}
        <Text onPress={this.goGouWu} style={styles.btn}>去結算{str}</Text>
      </ScrollView>
    );
  },
  goGouWu: function(){
    this.props.navigator.push({//通過導航組件,在觸發結算需求后跳轉到結算頁面
      component: GouWu,
      title:'購物車'
    });
  },
  press:function(data){
    var count = this.state.count;
    count ++;
    //改變數字狀態
    this.setState({
      count: count
    });
    //AsyncStorage存儲
    AsyncStorage.setItem('SP-' + this.genId() + '-SP', JSON.stringify(data), function(err){
      if(err){
        //TODO:存儲出錯
      }
    });
  },
  //生成隨機ID:GUID
  genId:function(){
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random() * 16 | 0,
          v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
      }).toUpperCase();
  }
});

var GouWu = React.createClass({
  getInitialState: function(){
    return {
      data: [],
      price: 0
    };
  },
  render: function(){
    var data = this.state.data;
    var price = this.state.price;
    var list = [];
    for(var i in data){
      price += parseFloat(data[i].price);
      list.push(
        <View key={i} style={[styles.row, styles.list_item]}>
          <Text style={styles.list_item_desc}>
            {data[i].title}
            {data[i].desc}
          </Text>
          <Text style={styles.list_item_price}>¥{data[i].price}</Text>
        </View>
      );
    }
    var str = null;
    if(price){
      str = ',共' + price.toFixed(1) + '元';
    }
    return(
      <ScrollView style={{marginTop:10}}>
        {list}
        <Text style={styles.btn}>支付{str}</Text>
        <Text style={styles.clear} onPress={this.clearStorage}>清空購物車</Text>
      </ScrollView>
    );
  },
  componentDidMount: function(){
    var _that = this;
    AsyncStorage.getAllKeys(function(err, keys){
      if(err){
        //TODO:存儲取數據出錯
        //如果發生錯誤,這里直接返回(return)防止進入下面的邏輯
      }
      AsyncStorage.multiGet(keys, function(errs, result){
        //TODO:錯誤處理
        //得到的結果是二維數組
        //result[i][0]表示我們存儲的鍵,result[i][1]表示我們存儲的值
        var arr = [];
        for(var i in result){
          arr.push(JSON.parse(result[i][1]));
        }
        _that.setState({
          data: arr
        });
      });

    });
  },
  clearStorage: function(){
    var _that = this;
    AsyncStorage.clear(function(err){
      if(!err){
        _that.setState({
          data:[],
          price: 0
        });
        alert('購物車已經清空');
      }
      //TODO:ERR
    });
  }
});
var Reactest = React.createClass({
  render: function() {
    return (
      <NavigatorIOS
        style={styles.container}
        initialRoute={
          {
            component: List,
            title: '水果列表'
          }
        }/>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  row:{
    flexDirection: 'row',
    marginBottom: 10,
  },
  item:{
    flex:1,
    marginLeft:5,
    borderWidth:1,
    borderColor:'#ddd',
    marginRight:5,
    height:100,
  },
  img:{
    flex:1,
    backgroundColor: 'transparent'
  },
  item_text:{
    backgroundColor: '#000',
    opacity: 0.7,
    color:'#fff',
    height:25,
    lineHeight:18,
    textAlign:'center',
    marginTop:74
  },
  btn:{
    backgroundColor:'#FF7200',
    height:33,
    textAlign:'center',
    color:'#fff',
    marginLeft:10,
    marginRight:10,
    lineHeight:24,
    marginTop:40,
    fontSize:18,
  },
  list_item:{
    marginLeft:5,
    marginRight:5,
    padding:5,
    borderWidth:1,
    height:30,
    borderRadius:3,
    borderColor:'#ddd'
  },
  list_item_desc:{
    flex:2,
    fontSize:15
  },
  list_item_price:{
    flex:1,
    textAlign:'right',
    fontSize:15
  },
  clear:{
    marginTop:10,
    backgroundColor:'#FFF',
    color:'#000',
    borderWidth:1,
    borderColor:'#ddd',
    marginLeft:10,
    marginRight:10,
    lineHeight:24,
    height:33,
    fontSize:18,
    textAlign:'center',
  }
});


AppRegistry.registerComponent('Reactest', () => Reactest);


最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容