Javascript for react
Javascript for React
2020/06/18 (補充內容)
2020/07/07 (新增連結)
2021/04/21 (補充內容)
基本概念
React是基於javascript,所以,大部分的語法都是javascript語法。以下的範例會以react為例,然而,這邊的重點在於解釋javascript語法,而不是react的運作原理,所以,以下內容都不會講解react的運作原理。
Class Component
以一個最簡單的react類別為例:
import React, { Component } from 'react';
class App extends Component {
render() {
return ();
}
}
export default App;
利用import就可以使用react定義的元件,這跟java的import類似。
import React, { Component } from 'react';
要讓別的檔案可以使用我們寫好的類別要使用export (詳參: 淺談JavaScript ES6的import與import{}及export及export default使用方式 )
export default App;
定義一個類別並繼承Component類別,在此類別中包含一個方法render,render是一個特別的方法,override已經定義在Component裡的方法,這個語法跟java很像,只是在javascript中不需要定義方法的回傳值資料型態:
class App extends Component {
render() {
return (
);
}
}
export default App;
Functional Component
在java裡都是以類別為最基本的單位,然而,javascript就不一定是。在react裡,可以利用function來寫一個元件。如果以函數(function)的方式,就沒有繼承的概念,也沒有override的概念,而且,因為是個函數,所以,要顯示的內容就寫在return裡,在javascript中不需要定義函數的回傳值資料型態,寫法是:
import React from 'react';
function App() {
return (
);
}
export default App;
比class的方式簡單多了。這也是react開發方式的未來主流,後面的介紹都會以functional component為例。這兩種方式的細節請詳見: Class Component、Functional Component。
object
在javascript裡,可以不用類別就可以定義物件 (類似php的associative array),例如:
product = {id:"0", desc:"iPad", price:20000};
console.log(product.desc);
//也可以
console.log(product["price"]);
//output:
//iPad
//20000
也可以在物件中定義函數,跟java不一樣的是,要取得變數要加"this":
product = {
id:"0",
desc:"iPad",
price:20000,
price_US: function(){
this.price * 30;
}
};
console.log(product.price_US());
array
在javascript也是有陣列,使用方式跟java很像:
products= [
{id:"0", desc:"iPad", price:20000},
{id:"1", desc:"iPhone X", price:30000}
];
console.log(products[0].desc);
//output:
//iPad
或者
products = new Array(
{id:"0", desc:"iPad", price:20000},
{id:"1", desc:"iPhone X", price:30000}
);
console.log(products[0].desc);
//output:
//iPad
可以結合迴圈,語法跟java很像:
products= [
{id:"0", desc:"iPad", price:20000},
{id:"1", desc:"iPhone X", price:30000}
];
for (i=0;i<products.length;i++){
console.log(products[i].desc);
}
更精簡的寫法:
products= [
{id:"0", desc:"iPad", price:20000},
{id:"1", desc:"iPhone X", price:30000}
];
for (product of products){
console.log(product.desc);
}
for迴圈除了用在陣列之外,也可以用在物件的變數:
products= [
{id:"0", desc:"iPad", price:20000},
{id:"1", desc:"iPhone X", price:30000}
];
for (product of products){
for (item of product){
console.log(item);
}
}
另一種寫法:
products= [
{id:"0", desc:"iPad", price:20000},
{id:"1", desc:"iPhone X", price:30000}
];
for (product of products){
for (index in product){
console.log(product[index]);
}
}
不過,除了利用迴圈之外,也可以利用陣列的iteration method,利用foreach(),foreach會呼叫一個function(call back method),將陣列的每一個元素傳過去:
products= [
{id:"0", desc:"iPad", price:20000},
{id:"1", desc:"iPhone X", price:30000}
];
products.foreach(getId);
function getId(value, index, array){
console.log(value.price);
}
//output:
//20000
//30000
也可以使用map(),map也會呼叫一個function(call back method),將陣列的每一個元素傳過去,第一個。
products= [
{id:"0", desc:"iPad", price:20000},
{id:"1", desc:"iPhone X", price:30000}
];
products.map(getId);
function getId(value, index, array){
console.log(value.price);
}
//output:
//20000
//30000
不同的是,map()可以回傳一個處理後的結果新的陣列:
products= [
{id:"0", desc:"iPad", price:20000},
{id:"1", desc:"iPhone X", price:30000}
];
products2 = products.map(processPrice);
function processPrice(value, index, array){
return "price:"+value.price;
}
console.log(products2[0]);
//output:
//price:20000
不過,一般不會這樣寫,而是搭配arrow function。
Destructuring
The Destructuring Assignment in JavaScript
Destructuring Syntax on Arrays
Destructuring Syntax on Objects
Swapping Variables
For…of Loop
Destructuring Arrays in JavaScript
Grabbing the First Element
Grabbing All Of The Elements
Grabbing Non-Sequential/Out Of Order Elements
Using the Spread Operator
Array Destructuring from an Object
Array Destructing from a Function
function
Function Declarations vs Function Expressions
兩種方法的使用還是有差別的,function的定義是可以寫在後面。
times(3,4);
function times(a,b) {
return a * b;
}
用expression的話,就不能這樣呼叫了!! 使用expression的好處是,因為是const,所以,不能重複定義,使用function時,如果重複定義,後面定義的function會覆蓋前面的function。更多的細節請參考:function 。
times(3,4);//times not defined
const times = function (a,b) {
return a * b;
}
Function Hoisting
Callback Pattern
Callbacks and Scope
Returning Functions
Lazy Function Definitions ( Self-Defining Functions )
Immediate Functions / Immediately-Invoked Functions (IIFEs)
Immediate Object Initialization
Function Properties — Memoization
Configuration Objects Pattern
arrow function
arrow function是個在ES6之後的新語法,是較精簡的寫法,對新手而言,是個不容易理解的語法。
ES5 (unnamed function expression)
const times = function (a,b) {
return a * b;
}
ES6: Arrow function (省略 大括號時,也省略return,計算結果就是回傳值)
const times = (a,b) => a*b;
map搭配arrow function
products= [
{id:"0", desc:"iPad", price:20000},
{id:"1", desc:"iPhone X", price:30000}
];
function getValue(value){ return value.price;};
console.log(products.map(getValue));
map結合arrow function:
products= [
{id:"0", desc:"iPad", price:20000},
{id:"1", desc:"iPhone X", price:30000}
];
console.log(products.map(value => {return value.price;}));
如果只有一行,可以省略大括號跟return:
products= [
{id:"0", desc:"iPad", price:20000},
{id:"1", desc:"iPhone X", price:30000}
];
console.log(products.map(value=>value.price));
在react裡,常常可以看到這樣的寫法,這樣寫的好處是,因為夾雜了html的語法,放在這裡比較容易看得懂:
return (
<ul>
{this.products.map(product => <li>{product.id} / {product.desc} / {product.price}</li>)}
</ul>
);
generator
Use JavaScript Generator Functions to Reduce Memory Utilization: A comparison of memory management for ordinary JavaScript functions and generator functions
What is a JS generator? It is a function that can return a value and then continue the execution of the function at a later time. Whereas an ordinary JS function uses a return operator, the generator function uses a yield operator.
function *numberToN(N) {
for (let i = 0; i < N; i ++) {
yield i;
}
}
JSON
JavaScript JSON / JSON - Introduction / JSON Syntax
Because of this similarity, a JavaScript program can easily convert JSON data into native JavaScript objects.
Because JSON syntax is derived from JavaScript object notation, very little extra software is needed to work with JSON within JavaScript.
JSON
{ "name":"John" }
Javascript object
{ name:'John' }
將JSON字串轉為javascript object (詳參: JSON.parse())
var obj = JSON.parse(text);
將javascript object轉為JSON字串 (詳參: JSON.stringify())
var myJSON = JSON.stringify(obj);
參考資料
javascript語法
JavaScript essentials for React developers
Variable Declaration
Classes (ES6)
Inheritance
Arrow functions (ES6)
Array.map()
Template Literals
Multi-line Strings
Object Destructuring (ES6)
Spread Operator
Modules
Must know JavaScript for react developers
Let & Const
Arrow functions
Destructuring
Default params, rest, and spread
The class syntax
Template literals
Modular JavaScript
Exports
Imports
Promises
A new feature was added in ES8 which builds on top of the idea of promises called async await. This builds on top of promises and you can refactor in either direction, so it’s important to first understand the concept of promises before using this alternative syntax.
All the JavaScript you need to know before starting with React
Block scopes and the var/let/const keywords
Arrow functions and closures
The literal notations
Expressions for React
Destructuring arrays and objects
The rest/spread syntax
Shorthand and dynamic properties
Promises and async/await
Modules import/export
Map, filter, and reduce
Conditional expressions
Timeouts and intervals
An Overview of Next-Generation JavaScript Features for React Apps
let and const
Arrow Functions
Imports and Exports
Classes
Classes and Defining Methods
Classes and Inheritance
Spread and Rest Operator
Destructuring
Function
Three Ways to Define Functions in JavaScript
Function Declaration
Function Expression
Generator Function
Arrow function
A Beginner’s Guide to Arrow Functions in ES6: Part 1
array.map() with arrow function
When (and why) you should use ES6 arrow functions — and when you shouldn’t
JavaScript Arrow Functions: How, Why, When (and WHEN NOT) to Use Them
JavaScript arrow functions are roughly the equivalent of lambda functions in python or blocks in Ruby.