ReactNative 踩坑小计

  • 使用ES6語法編寫Component時綁定事件需要用this.MethodName.bind(this),否則MethodName中無法使用this
    <TouchableHighlight onPress={this.onPressButton.bind(this)}>
        <Text>Test</Text>
    </TouchableHighlight>
  • 使用ES6語法編寫方法,需要調用同類中的方法時,需要添加this前綴,否則會出現無法找到function錯誤
    getSomeVar(){
        return this.someVar;
    }
    testMethod(){
        return this.getSomeVar();
    }
  • node_gyp
    有些npm安裝包需要node_gyp,此程序需要先安裝python,  且只支持2.7版本 ,3.X是不支持的,安裝時注意將安裝目錄添加至PATH選項,如未勾選請自行加上

  • 運行github上面的項目example步驟:
    1.進入項目example目錄運行npm install
    2.運行 react-native upgrade
    3.如遇到__DEV__ is not defined 錯誤,請移除.babelrc裏的"presets": ["react-native"]
  • ListView刷新行數據需要注意點【PressRow】:
    1.新數據集需要先克隆
    2.修改行數據為對象時需要采用對像方式賦值,而且不是obj.propTest='Value'
    3.更新數據源採用this.setState方法
    pressRow(rowData, rowID){
        let newArray = this.state.itemData.slice();  //數組複製
        newArray[rowID] = {                          //對象式賦值
          ...this.state.itemData[rowID],
          ChangeValue: 'TestValue',
        };
        this.setState({                              //更新數據源
          itemDataSource: this.state.itemDataSource.cloneWithRows(newArray),
        });
      }
  • 當ListView的dataSource數據來源為對像數組時,刷新整個數據需要對數組重新賦值,否則不會刷新頁面:
    方法1:
    let newArray=this.state.data.slice();
    for (var i = 0; i < newArray.length; i++) {
      newArray[i]={
        ...this.state.data[i],
      };
    }
    this.setState({
      dataSource:this.state.dataSource.cloneWithRows(newArray),
    });
    方法2:
    let newArray=JSON.parse(JSON.stringify(this.state.data));
    this.setState({
      dataSource:this.state.dataSource.cloneWithRows(newArray),
    });
  • 調試anrdoid時有時候Reload JS無效,這時候請關閉原來的JS Running窗口,執行 react-native start試試
  • 導入Class時需要注意導入類是否包含defalut,default為不帶括號,非default需要帶括號,否則有可能會引起錯誤
    import Games from './views/Games';
    import {Login} from './views/Login';
    
    export default class Games extends Component {
      ..........  
    }
    
    export class Login extends Component {
    }
  • ES6类中constructor 引用静态变量不会执行 New实例的时候会执行。
  • 第一个页面有獲得焦點的TextInput控件时,須在轉到第二個頁面前取消焦點,否則轉到第二个页面为Listview时绑定行必须要点两次才会触发
    注:用的是react-native-router-flux 中的 Actions.pageKey()方法.
  • react-native-store用for删除多笔带条件数据时,需要添加async和await,否则只会删除第一笔
    static async clearCart(items){
      for (let item of items) {
        await DB.Cart.remove({
                        where:{
                          and:[{id:item.ID}]
                        }
                      });
      }
    }
原文地址:https://www.cnblogs.com/ywkpl/p/5562829.html