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
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,因為它的模式會讓我們把程式碼拆的越多而已。
转载请注明:XAMPP中文组官网 » DAY26:用counter來了解redux