初學 React Native 時在 fetch(...).then(response => response.json()) 看到 =>,以為是 React 專屬語法,實則為 ES6 箭頭函式。
(參數) => { 函式主體 } // 完整寫法
(參數) => 表達式 // 隱式回傳,單行時可省略大括號與 return
() => { ... } // 無參數
x => x * 2 // 單參數可省略括號
this,會捕獲定義時的上下文,避免 bind(this) 或 var self = this。map/filter、Promise 鏈均更易閱讀。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,需用其餘參數 (...args) => {}。const fetchData = async () => {
try {
const res = await fetch(url);
return await res.json();
} catch (e) {
console.error(e);
}
};
=> 是 ES6 箭頭函式,非 React 專屬。掌握其 this 詞法綁定與簡潔語法,能大幅提升 React Native 開發效率與程式碼可讀性。