首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

React Native 中的 => 箭頭函式詳解

     編輯:程式設計綜合問答

問題來源

初學 React Native 時在 fetch(...).then(response => response.json()) 看到 =>,以為是 React 專屬語法,實則為 ES6 箭頭函式。

箭頭函式基礎語法

(參數) => { 函式主體 }        // 完整寫法
(參數) => 表達式             // 隱式回傳,單行時可省略大括號與 return
() => { ... }                // 無參數
x => x * 2                   // 單參數可省略括號

為何在 React / RN 中大量使用

  1. this 綁定:箭頭函式沒有自己的 this,會捕獲定義時的上下文,避免 bind(this) 或 var self = this。
  2. 簡潔:回調函式、map/filter、Promise 鏈均更易閱讀。
  3. 類別屬性寫法:handleClick = () => { ... } 直接綁定實例,無需建構式綁定。

原題代碼對照

// 原寫法
fetch(query)
  .then(response => response.json())                    // 隱式回傳 response.json()
  .then(json => this._handleResponse(json.response))      // 傳遞 json.response
  .catch(error => this.setState({                         // 錯誤處理
    isLoading: false,
    message: 'Something bad happended' + error
  }));

// 等價的傳統函式寫法
fetch(query)
  .then(function(response) { return response.json(); })
  .then(function(json) { return this._handleResponse(json.response); }.bind(this))
  .catch(function(error) {
    this.setState({ isLoading: false, message: 'Something bad happended' + error });
  }.bind(this));

常見誤區

  • 非適用於物件方法簡寫:const obj = { method: () => {} } 會導致 this 指向全域,應用 method() {}。
  • 無法作為建構式:new (() => {}) 會拋錯。
  • arguments 物件:箭頭函式無 arguments,需用其餘參數 (...args) => {}。

進階:非同步箭頭函式

const fetchData = async () => {
  try {
    const res = await fetch(url);
    return await res.json();
  } catch (e) {
    console.error(e);
  }
};

總結

=> 是 ES6 箭頭函式,非 React 專屬。掌握其 this 詞法綁定與簡潔語法,能大幅提升 React Native 開發效率與程式碼可讀性。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved