Redux

Redux

核心概念(core concepts)

  • 資料(state):一個物件,包含所有的資料狀態。
    • Globalized State
  • 動作(action):一個物件,用來描述對資料要進行什麼樣的操作。
    • Increment
  • reducer:一個函式,根 action 的描述對原有的資料進行變更。
  • Dispatch

三個原則(three principles)

  • Single source of truth:整個 App 的資料狀態(state)都保存在單一的物件中,這個保存所有資料的物件稱作 store。
  • State is read-only:要改變資料狀態的唯一方式就是透過 action。
  • Change are made with pure functions:reducers 是一個單純的函式,它會根據 action 和原有的 state,再不變更原有 state 的情況下回傳新的 state。

Store

  • 會擁有整個 App 的 state,在 Redux 中總是只會有一個 store,但可以有多可 reducer。
  • 當 state 有更新時,store 會通知有訂閱的 container 有新的 state。
  • 透過 getState() 可以取得 state 的資料。
  • 透過 dispatch(action) 可以更新 state 的資料。
  • 透過 subscribe(listener) 可以註冊監聽事件。

缺點

  • 共享單一Data Store
    • 在取 state/action 名的時候都要格外小心 naming collision
  • 額外的學習門檻,環境設定,也很難讓人馬上上手。

實作

  • 每個 action 一定是個物件,且要包含 type 屬性,其他選擇性的屬性包含 error, payload, meta,任何其他名稱的屬性都是不被允許的。
  • reducer 一定要是 pure function,也就是要回傳新的 state(immutable)
  • 不要在裡面呼叫 API,這些不允許的行為都應該在 store.dispatch(action) 之前處理。
  • 所有的 reducer 都會接收到 action,並回傳 state,這個資料狀態有可能是新的或舊的。
npm install redux react-redux
import {createStore} from 'redux';

const increment = () => {
  return {
    type: 'INCREMENT'
  }
}

const counter = (state = 0, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return state + 1;
      break;
    default:

  }
}


let store = createStore(counter);

store.subscribe(()=>console.log(store.getState()));
store.dispatch(increment());
import {createStore} from 'redux';
import {Provider} from 'react-redux';

const store = createStore(allReducer);

ReactDOM.render(
  <Providor store="store">
    <App />
  </Providor>

);
import {useSelector, useDispatch} from 'react-redux';
import { increment } from './actions'

const counter = useSelector(state => state.counter)
const isLogged = useSelector(state => state.isLogged)
const dispatch = useDispatch();


return (
  <button onClick={() => dispatch(increment())}}>
  +
  </button>
)

參考資料

2021

教學影片

2022

2019