Tekkaman

导航

 

Redux

1、Redux 的设计思想  

  (1)Web 应用是一个状态机,视图与状态是一一对应的。

  (2)所有的状态,保存在一个对象里面。

2、Store

  Store 就是保存数据的地方,你可以把它看成一个容器。整个应用只能有一个 Store。

  Redux 提供createStore这个函数,用来生成 Store。当前时刻的 State,可以通过store.getState()拿到。

  import { createStore } from 'redux';
  const store = createStore(fn);
  const state = store.getState();

3、Action

  Action 是一个对象。其中的type属性是必须的

  const action = {
    type: 'ADD_TODO',
    payload: 'Learn Redux'
  };

  Action Creator。可以定义一个函数来生成 Action,这个函数就叫 Action Creator。

const ADD_TODO = '添加 TODO';

function addTodo(text) {
  return {
    type: ADD_TODO,
    text
  }
}

const action = addTodo('Learn Redux');

4、store.dispatch()

  store.dispatch()是 View 发出 Action 的唯一方法。

  

5、reducer

  Reducer 是一个函数,它接受 Action 和当前 State 作为参数,返回一个新的 State。  

  

  store.dispatch方法会触发 Reducer 的自动执行。在生成 Store 的时候,将 Reducer 传入createStore方法。

  纯函数是函数式编程的概念,必须遵守以下一些约束。

  • 不得改写参数
  • 不能调用系统 I/O 的API
  • 不能调用Date.now()或者Math.random()等不纯的方法,因为每次会得到不一样的结果

  Reducer 函数里面不能改变 State,必须返回一个全新的对象,请参考下面的写法。

  

6、store.subscribe()

  store.subscribe方法返回一个函数,调用这个函数就可以解除监听。

  

参考:

1、http://www.ruanyifeng.com/blog/2016/09/redux_tutorial_part_one_basic_usages.html

posted on 2017-04-29 15:41  Tekkaman  阅读(232)  评论(0编辑  收藏  举报