Object

let fruits = {
  apple: 2,
  banana: 3,
  orange: 1
};

fruits是一個物件,一個 property 代表一種水果,key 是水果名稱,value 是數量

// Object.keys
let object = {a: 1, b: 2, c: 3};
console.log(Object.keys(object));  // ["a", "b", "c"]

// Object.values
let object = {a: 1, b: 2, c: 3};
console.log(Object.values(object));  // [1, 2, 3]

// Object.entries
let object = {a: 1, b: 2, c: 3};
console.log(Object.entries(object));
// [
//   ["a", 1],
//   ["b", 2],
//   ["c", 3]
// ]

Hoisting

hoisting 重點:

  1. 變數宣告跟函式宣告都會提升
  2. 只有宣告會提升,賦值不會提升
  3. 別忘了函式裡面還有傳進來的參數

我知道你懂 hoisting,可是你了解到多深? · Issue #34 · aszx87410/blog

Callback function, sync and async

JavaScript 中的同步與非同步(上):先成為 callback 大師吧!

Import and Export

完全解析 JavaScript import、export

ES5 vs ES6+

React ES5、ES6+ 常見用法對照表

Promise

Promise async await

Curry(柯里化)

JSX裡面寫function

如果直接寫 fun()

編譯後他會馬上執行,所以通常才寫成fun而非fun()

且畫面每更新一次,JSX都會執行,所以寫fun()會執行很多次,可能造成不預期的結果

例如

const fun = () => {doSomething()}

<Component onClick={fun} />     //不會直接執行
<Component onClick={fun()} />   //會直接執行

如果要在JSX的function裡面帶參數,可以有幾種寫法:

const fun = (para) => () => {dosomething(para)}

<Component onClick={fun(para)} />
const fun = (para) => {dosomething(para}

<Component onClick={()=>{fun(para}} />
cosnt [paraState, setParaState] = useState(para)

const fun = () => {dosomething(paraState)}

<Component onClick={fun} />

第 4 章:Curry(柯里化)

邏輯運算子

邏輯 AND 要兩個都 true 才算 true

<aside> 💡 左→右逐個檢查。 遇到任一個false,直接回傳false。 檢查到最後全都ture,直接回傳最後的true值

</aside>

只要有任一個false,就回傳false

只要兩個都true,就回傳最後一個

var a1 =  true && true;     // t && t 回傳 true
var a2 =  true && false;    // t && f 回傳 false
var a3 = false && true;     // f && t 回傳 false
var a4 = false && (3 == 4); // f && f 回傳 false
var a5 = "Cat" && "Dog";    // t && t 回傳 Dog
var a6 = false && "Cat";    // f && t 回傳 false
var a7 = "Cat" && false;    // t && f 回傳 false

邏輯 OR 只要一個 true 就算 true

<aside> 💡 左→右逐個檢查。 遇到任一個true,直接回傳那個true值。 檢查到最後全都false,就回傳false

</aside>

只要有任一個true,就回傳那個(如全都true,就回傳第一個)

如全都false,就回傳false

var o1 =  true || true;     // t || t 回傳 true
var o2 = false || true;     // f || t 回傳 true
var o3 =  true || false;    // t || f 回傳 true
var o4 = false || (3 == 4); // f || f 回傳 false
var o5 = 'Cat' || 'Dog';    // t || t 回傳 Cat
var o6 = false || 'Cat';    // f || t 回傳 Cat
var o7 = 'Cat' || false;    // t || f 回傳 Cat

應用:當某個條件達成,就渲染某個component (執行某個fun)

例如:當通知的array長度>0,就渲染 <Notification/>

import Notificaiont from './Notification'

const App = ({ notifications, ...props }) => {
	// ...
	return (
		// ...
		{notifications.length > 0 && <Notification /> }
	)
}

Reading in sequence

If you want to read the files in sequence, you cannot use forEach indeed. Just use a modern for … of loop instead, in which await will work as expected:

async function printFiles () {
  const files = await getFilePaths();

  for (const file of files) {
    const contents = await fs.readFile(file, 'utf8');
    console.log(contents);
  }
}

Reading in parallel

If you want to read the files in parallel, you cannot use forEach indeed. Each of the async callback function calls does return a promise, but you're throwing them away instead of awaiting them. Just use map instead, and you can await the array of promises that you'll get with Promise.all:

async function printFiles () {
  const files = await getFilePaths();

  await Promise.all(files.map(async (file) => {
    const contents = await fs.readFile(file, 'utf8')
    console.log(contents)
  }));
}

Using async/await with a forEach loop

⚛️ React

Links

kdchang/reactjs101

React.Component

class ShoppingList extends React.Component {
  render() {
    return (
      <div className="shopping-list">
        <h1>Shopping List for {this.props.name}</h1>
        <ul>
          <li>Instagram</li>
          <li>WhatsApp</li>
          <li>Oculus</li>
        </ul>
      </div>
    );
  }
}

// 使用範例:<ShoppingList name="Mark" />

在這裡,ShoppingList 是一個 React 的 component class,或 React component type。Component 會接受名為 props 的參數(「properties」的簡稱),並透過 render 這個方法回傳一個有階層架構的 view 到螢幕上。

render 方法回傳你想在螢幕上看到的描述。React 接收這個描述並展示其結果。其中,render 回傳的是一個 React element,也就是一個 render 內容的輕量描述。

大部分 React 的開發者會使用一種特殊的語法,被稱為「JSX」,因為它讓這些結構寫起來更容易。<div /> 語法在構建時被建立為d

也可以不使用JSX,使用 createElement()

return React.createElement('div', {className: 'shopping-list'},
  React.createElement('h1', /* ... h1 children ... */),
  React.createElement('ul', /* ... ul children ... */)
);

Start a project

npx create-react-app my-app
cd my-app
npm start
# or
yarn start

Hook

Hook 是一個讓你可以使用 React 各項功能的特殊 function

舉例來說,useState 是一個讓你增加 React state 到 function component 的 Hook。

import React, { useState } from 'react';

function Example() {
  // 宣告一個新的 state 變數,我們叫他「count」
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

這裡,useState 是一個 Hook 。我們在 function component 中呼叫他們用來加入一些 local state。React 會在重新 render 的頁面之間保留這些 state。

useState 回傳一組數值:目前 state 數值和一個可以讓你更新 state 的 function。

你可以從 event handler 或其他地方呼叫這個 function 來更新他。很類似 this.setState 在 class 當中的用法,除了他不會將舊的與新的 state 合併在一起。(我們將會在使用 State Hook 中示範一個範例比較 useState 與 this.state。)

useState 唯一的 argument 是初始狀態。在上面的例子中,他是 0 因為我們的計數器從零開始。注意不像 this.state,state 在這裡不需要一定是 object,雖然你要也可以。初始狀態 argument 只有在第一次 render 的時候會被用到。

使用 State Hook - React

useState is a hook used to maintain local states in function components.

useEffect is used to execute functions after a component gets rendered (to “perform side effects”).

Fetching Data in React using Hooks

The second argument can be used to define all the variables (allocated in this array) on which the hook depends. If one of the variables changes, the hook runs again.

How to fetch data with React Hooks? - RWieruch

Hook setState 之後馬上使用

方法1:使用useEffect

useEffect(() => {
    // you will get updated finalData here, each time it changes
    console.log(finalData);
    // you can trigger your function from here
},[finalData]);

https://stackoverflow.com/questions/61812978/updating-a-state-immediately-using-react-hooks

方法2:Calling updater just to get the latest value.

const [value, setValue] = useState("");
setValue("React is awesome!");
setValue((state) => {
  console.log(state); // "React is awesome!"
  
  return state;
});

方法3:Custom hook for setState with async state selector.

const [value, setValue, getValue] = useSetState("");
setValue("React is awesome!");
console.log(await getValue()); // "React is awesome!"

cf: https://medium.com/ableneo/react-setstate-does-not-immediately-update-the-state-84dbd26f67d5

React

JS - make array