十分钟理解Redux核心思想,过目不忘。

白话Redux工做原理。浅显易懂。
若有纰漏或疑问,欢迎交流。

Redux 约法三章

惟一数据源(state)

虽然redux中的statereact没有联系,但能够简单理解为react组件中的this.state
html文档只是state的一种表现形式。全部html的数据应该都是直接间接来自于state,不然UI视图是没法因state改变而更新的。html

数据源(state)只读

不该该直接修改state数据。
对于数组使用:react

Array.prototype.slice()//对数组进行拷贝
//使用ES6: 
[...state, ...newState]

对于对象使用:编程

Object.assign({}, state, change1, change2...)//对对象进行拷贝
//使用ES6:
{...state, ...newState}

经过纯函数(pure function)改变数据源(state)

pure function: 无其余API(包括Math, Date等)调用,无异步操做,preState => newState。redux

Redux数据流

简单介绍store/reducer/action, 比较简洁,请牢记于心。数组

store
UI惟一数据来源,能够理解为react中的state,store信息的变化会触发视图更新.异步

action
对象。必须拥有type属性,用来描述发生什么。可选择携带发生时的数据,如用户输入的input value。切记:仅仅用来表述发生了什么。函数

reducer
pure function(上面有解释)。根据action.type来作出反应,(preState, action) => newState,生成的state是用来改变store的。学习

因此,data flow(数据流):this

  1. UI发出动做,如click, submit;
  2. action, 描述发生了什么;
  3. reducer处理发生的事情,生成新state;
  4. store被更新;
  5. UI响应store更新
  6. ...

Redux action

举几个例子,可能会比较直观:spa

{
  type: “TOGGLE_TODO”, //这个type属性必需要,必须是字符串
  index: 5 //附加信息,本身根据须要选择是否加入
};
{
  type: “ADD_TODO”,
  text:“学习Redux” //附加信息,这里是input value
}

没别的,就是这么简单。
有时候可使用action生成器(action creators)来批量生产类似action对象,如:

//我须要根据不一样的input value来生成高度类似的action:
function (text) {
  return {
    type: "ADD_TODO",
    text: text //附加的信息
  }
}

说明
虽然上面数据流提到,action经过reducer处理生成newState后才可以更改store信息。可是为了更好的语义编程,Redux经过语句store.dispatch(action)来更新store,reducer对action的处理在内部处理。

Redux reducer

很简单

(theState, action) => (newState);
//仅仅只是根据action.type处理一下须要更新的state

来看一个相对完整的reducer:

function todoApp(state = initialState, action) { //注意须要处理undefined状况下的state默认值
  switch (action.type) {  //根据action.type来判断
    case "SET_VISIBILITY_FILTER":
      return Object.assign({}, state, {
        visibilityFilter: action.filter
      })
    case “ADD_TODO”:  //处理“ADD_TODO”的action type
      //返回新state(newState),注意不要直接改变state,对象使用了
      //Object.assign()。也可使用ES的...操做符
      return Object.assign({}, state, {
        todos: [
          ...state.todos,
          {
            text: action.text,
            completed: false
          }
        ]
      })
    case “TOGGLE_TODO”:  //处理“TOGGLE_TODO”的action type
      return Object.assign({}, state, {
        todos: state.todos.map((todo, index) => {
          if (index === action.index) {
            return Object.assign({}, todo, {
              completed: !todo.completed
            })
          }
          return todo
        })
      })
    default:
      return state
  }
}

Redux store

store
UI视图惟一数据来源(直接或间接),能够获取state,更新state,监听state变化,取消监听。因此store提供了一下方法:

  1. store.getState() 获取当前state
  2. store.dispatch(action) 更新state
  3. store.subscribe(listener) store更新后回调listener,回调函数里面能够调用store.getStore()来获取更新后得state哟~
  4. 取消listener的方式比较特别:调用一次store.subscribe(sameListner)

ps: 若有纰漏或疑问,欢迎交流。先写这么多,有时间继续更新。

相关文章
相关标签/搜索