Redux01 續集

subscribe()

import { createStore } from "redux"

/*新建stoore
*通過reducer 建立
*根據老的狀態和action,生成新的state   */

function counter (state=0,action){
    switch(action.type){
        case "加機關槍":
            return state + 1
        case "減機關槍":
            return state - 1
        case "搶機關槍":
            return state * 1000
        default:
        return 10
    }
}

const  store =  createStore(counter)

/*新建store 結束*/

const init = store.getState()

console.log(init)

function listener(){
    const cur = store.getState()
    console.log(`現在有機槍  ${cur}把`)
}

store.subscribe(listener)

/*  派發事件 傳遞action    */

store.dispatch({type: "加機關槍"})


store.dispatch({type: "加機關槍"})


store.dispatch({type: "減機關槍"})


store.dispatch({type: "搶機關槍"})
















發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章