0x000 概述
这一章讲一些栗子
0x001 原生+redux
完成counter
修正模板
<!doctype html> <html> <head> <title>React Study</title> </head> <body> <div id="app"> <p id="counter">0</p> <button id="btnAdd">增添</button> <button id="btnSub">削减</button> </div> </body> </html>
修正进口文件
import {createStore} from 'redux' // 声明两个 action const ACTION_NUM_INCREMENT = 'ACTION_NUM_INCREMENT' const ACTION_NUM_DECREMENT = 'ACTION_NUM_DECREMENT' // 声明一个 reducer const counter = (state = 0, action) => { switch (action.type) { case ACTION_NUM_INCREMENT: { return ++state } case ACTION_NUM_DECREMENT: { return --state } default : { return state } } } let store = createStore(counter) // 设置监听, 当 reducer 发作转变的时刻猎取新的 counter, 并更新界面 store.subscribe(() => { document.getElementById('counter').innerText = store.getState() }) // 绑定事宜 document.getElementById('btnAdd').addEventListener('click', () => { store.dispatch({type: ACTION_NUM_INCREMENT}) }) document.getElementById('btnSub').addEventListener('click', () => { store.dispatch({type: ACTION_NUM_DECREMENT}) })
检察浏览器
申明:dispatch
实在就是发出一个要求,比方store.dispatch({type: ACTION_NUM_INCREMENT})
发出的实际上是一个增添
的要求,固然这个只是一个名字罢了,怎样处置惩罚还看我们本身,是一个简朴的js
对象,我们发出这个要求今后,reducer
将会遭到这个要求,counter
中的action
对象实在就是你发出的这个东西,经由switch
处置惩罚今后,将会吧reducer
返回值作为新的state
保存起来,并关照定阅了store
的处所–subscribe
的回调函数将会实行。
0x002 运用ledux
运用ledux
完成也很简朴上诉的代码只需要该两个处所就好了
导入
Ledux
import Ledux from "../../0x101-hello-redux/src/ledux";
修正
createStore
为Ledux.createStore
//redux // let store = createStore(counter) //ledux let store = Ledux.createStore(counter)
如许就好了
0x003 运用MyEvent
完成
运用MyEvent
完成没法复用现有的,然则也很简朴
import MyEvent from "../../0x012-component-communication/src/MyEvent";
// 声明两个 action
const ACTION_NUM_INCREMENT = 'ACTION_NUM_INCREMENT'
const ACTION_NUM_DECREMENT = 'ACTION_NUM_DECREMENT'
let counter = 0
MyEvent.sub(ACTION_NUM_INCREMENT, () => {
document.getElementById('counter').innerText = counter
})
MyEvent.sub(ACTION_NUM_DECREMENT, () => {
document.getElementById('counter').innerText = counter
})
// 绑定事宜
document.getElementById('btnAdd').addEventListener('click', () => {
++counter
MyEvent.pub(ACTION_NUM_INCREMENT)
})
document.getElementById('btnSub').addEventListener('click', () => {
--counter
MyEvent.pub(ACTION_NUM_DECREMENT)
})
0x004 总结
无