iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 26
0
Modern Web

30天React從入門到入坑系列 第 26

DAY26:用counter來了解redux

redux counter example

import { createStore } from 'redux'

//reducer function
function counter(state = 0, action) {
  switch (action.type) {
  case 'INCREMENT':
    return state + 1
  case 'DECREMENT':
    return state - 1
  default:
    return state
  }
}

let store = createStore(counter)

store.subscribe(() =>
  console.log(store.getState())
)

store.dispatch({ type: 'INCREMENT' })
// 1
store.dispatch({ type: 'INCREMENT' })
// 2
store.dispatch({ type: 'DECREMENT' })
// 1

redux simple flow
https://ithelp.ithome.com.tw/upload/images/20180114/20107317BDGUxNQ0NM.png

Actions
actions就是傳遞到store的資訊(payload),它們是store唯一的資料來源,你可以藉由store.dispatch()傳入actions來改變內部的state。

{ type: 'INCREMENT' }

Reducer
reducer只是一個pure function,它接收(state, action)產生下一個新的state,reducer根據不同action來決定返回不同的state。

Store
store是redux的一個容器,用來保存整個應用程式的state。

Flux與Redux的不同
redux沒有dispatcher或支援多個store,它只有一個store和reducer function,所以有任何問題只要檢查store就可以了解所有state的變化。


redux其實跟flux很像,由於還在初心者階段儘量了解為何要使用,使用這些pattern為我們解決了什麼問題。尚在學習階段,先拿redux github上的介紹來了解redux的概念,redux作者寫了一篇"You Might Not Need Redux",如果我們不知道為何要用redux也就不必使用redux,因為它的模式會讓我們把程式碼拆的越多而已。

參考資料
redux github
https://github.com/reactjs/redux
You Might Not Need Redux
https://medium.com/@dan_abramov/you-might-not-need-redux-be46360cf367


上一篇
DAY25:flux想解決什麼問題?
下一篇
DAY27:react-redux simple counter
系列文
30天React從入門到入坑30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言