Redux示例1-概念

认识几个概念

1.Store

Store保存数据的地方,可以看作一个容器。

Redux提供createStore来生成store。

// 定义一个store,存储数据

var store = Redux.createStore(counter)

counter为定义的一个function。

2.State

Store包含所有的数据,可以通过store.getState()拿到

var state = store.getState()

3.Action

Action就是View发出的通知,表示State应该要发生变化了。

// 定义action

var actions = [

{ type: 'INCREMENT' },

{ type: 'DECREMENT' }

]

提及下Action Creator

其实就是通过函数的方式来定义一个Action,通过return一个对象出来。

4.store.dispatch()

// 增加事件

document.getElementById('increment')

.addEventListener('click', function(){

// 分发action

store.dispatch(actions[0])

})

// 减少事件

document.getElementById('decrement')

.addEventListener('click', function(){

// 分发action

store.dispatch(actions[1])

});

5.store.subscribe()

// 订阅状态变化

store.subscribe(render)

6.Reducer

是一个纯函数,就是计算state的数据

const reducer=function(state,action){// ...returnnew_state;};

示例中的代码为:

// 定义一个函数Reducer,实现增加和减少

function counter(state, action) {

if(typeof state === "undefined") {

return 0

}

// 当定义的action的type

switch (action.type) {

case 'INCREMENT':

return state + 1

case 'DECREMENT':

return state - 1

default:

return state

}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • http://gaearon.github.io/redux/index.html ,文档在 http://rac...
    jacobbubu阅读 80,153评论 35 198
  • 该文章仅作为个人笔记在使用redux的时候,避免不了的就是创建各种action和actionCreator等,有没...
    Tim张阅读 3,442评论 3 1
  • 学习必备要点: 首先弄明白,Redux在使用React开发应用时,起到什么作用——状态集中管理 弄清楚Redux是...
    贺贺v5阅读 8,994评论 10 58
  • 一、认识Redux 安装 npm install --save redux npm install --save ...
    SunshineMS阅读 399评论 0 2
  • 简单易懂的Redux 根据redux官方文档来说,可以将redux分为三个核心部分。 actions reduce...
    凉风hi阅读 1,045评论 0 0