Redux 基础概念

Redux is a predictable state container for JavaScript apps.,亦即 Redux 希望能提供一个可以预测的 state 管理容器,让开发者可以可以更容易开发复杂的 JavaScript 应用程式(注意 Redux 和 React 并无相依性,只是和 React 可以有很好的整合)。
 
三、基本概念和 API
 
Redux提供createStore 这个函数。用来生成Store
 
 
import { createStore } from 'redux';
 
const store = createStore(fn)
 
createStore函数接受另一个函数作为参数,返回新生成的store对象
 
 
3.2 State
 
 
State 对象包含所有的数据。如果想要得到某个时点的数据,
就要对 Store 生成快照。这种时点的数据集合,就叫做 State。
 
当前时刻的State,可以通过Store.getState()拿到
 
import { createStore } from 'redux';
const store = createStore(fn);

const state = store.getState();
 
Redux 规定, 一个 State 对应一个 View。只要 State 相同,View 就相同。你知道 State,就知道 View 是什么样,反之亦然。
 
3.3Action
 
State 的变化,会导致 View 的变化。但是,用户接触不到 State,只能接触到 View。所以,State 的变化必须是 View 导致的。Action 就是 View 发出的通知,表示 State 应该要发生变化了。
 
Action是一个对象。其中type属性是必须的,表示Action 的名称
 
const action = {
  type: 'ADD_TODO',
  payload: 'Learn Redux'};
 
上面代码中,Action 的名称是ADD_TODO,它携带的信息是字符串Learn Redux
可以这样理解,Action 描述当前发生的事情。改变 State 的唯一办法,就是使用 Action。它会运送数据到 Store。
 
3.4Action Createor
View 要发送多少种消息,就会有多少种 Action。如果都手写,会很麻烦。可以定义一个函数来生成 Action,这个函数就叫 Action Creator。
const ADD_TODO = '添加 TODO';

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

const action = addTodo('Learn Redux');
 
上面代码中,addTodo函数就是一个Action Creator
 
3.5  store.dispatch()
 
store.dispatch()是 View 发出 Action 的唯一方法。
 
import { createStore } from 'redux';
const store = createStore(fn);

store.dispatch({
  type: 'ADD_TODO',
  payload: 'Learn Redux'});
 
上面代码中,store.dispatch接受一个 Action 对象作为参数,将它发送出去。
结合 Action Creator,这段代码可以改写如下。
 
store.dispatch(addTodo('Learn Redux'));
 
3.6 Reducer——一个纯函数
 
Store 收到 Action 以后,必须给出一个新的 State,这样 View 才会发生变化。这种 State 的计算过程就叫做 Reducer。
Reducer 是一个函数,它接受 Action 和当前 State 作为参数,返回一个新的 State。
 
const reducer = function (state, action) {
// ...
  return new_state;
};
 
整个应用的初始状态,可以作为state的默认值
 
const defaultState = 0;
const reducer = (state = defaultState, action) => {
  switch (action.type) {
    case 'ADD':
      return state + action.payload;
    default:
      return state;
  }};

const state = reducer(1, {
  type: 'ADD',
  payload: 2    
});
 
//当前reducer返回的state重新赋值给state
 
上面代码中,reducer函数收到名为ADD的 Action 以后,就返回一个新的 State,作为加法的计算结果。其他运算的逻辑(比如减法),也可以根据 Action 的不同来实现。
实际应用中,Reducer 函数不用像上面这样手动调用,store.dispatch方法会触发 Reducer 的自动执行。为此,Store 需要知道 Reducer 函数,做法就是在生成 Store 的时候,将 Reducer 传入createStore方法。
 
import { createStore } from 'redux';
const store = createStore(reducer);
 
上面代码中,createStore接受 Reducer 作为参数,生成一个新的 Store。以后每当store.dispatch发送过来一个新的 Action,就会自动调用 Reducer,得到新的 State。
为什么这个函数叫做 Reducer 呢?因为它可以作为数组的reduce方法的参数。请看下面的例子,一系列 Action 对象按照顺序作为一个数组。
 
const actions = [
  { type: 'ADD', payload: 0 },
  { type: 'ADD', payload: 1 },
  { type: 'ADD', payload: 2 }];

const total = actions.reduce(reducer, 0); // 3
 
上面代码中,数组actions表示依次有三个 Action,分别是加0、加1和加2。数组的reduce方法接受 Reducer 函数作为参数,就可以直接得到最终的状态3
 
3.7纯函数
 
Reducer 函数最重要的特征是,它是一个纯函数。也就是说,只要是同样的输入,必定得到同样的输出。
纯函数是函数式编程的概念,必须遵守以下一些约束。
 
不得改写参数
不能调用系统 I/O 的API
不能调用Date.now()或者Math.random()等不纯的方法,因为每次会得到不一样的结果
 
 
由于reducer是纯函数。就可以保证同样的state,必定得到同样的View。正是因为这一点,Reducer函数里面不能改变State,必须返回全新的对象。
 
// State 是一个对象
function reducer(state, action) {
  return Object.assign({}, state, { thingToChange });
// 或者
  return { ...state, ...newState };}
// State 是一个数组
function reducer(state, action) {
  return [...state, newItem];}
 
最好把 State 对象设成只读。你没法改变它,要得到新的 State,唯一办法就是生成一个新对象。这样的好处是,任何时候,与某个 View 对应的 State 总是一个不变的对象。
 
 
3.8 store.subscribe()
Store 允许使用store.subscribe方法设置监听函数,一旦 State 发生变化,就自动执行这个函数。
 
import { createStore } from 'redux';
const store = createStore(reducer);

store.subscribe(listener);
显然,只要把 View 的更新函数(对于 React 项目,就是组件的render方法或setState方法)放入listen,就会实现 View 的自动渲染。
 
store.subscribe方法返回一个函数,调用这个函数就可以解除监听。
let unsubscribe = store.subscribe(() =>
  console.log(store.getState()));

unsubscribe();
四、Store 的实现
 
- store.getState()
 
- store.dispatch()
 
- store.subscribe()
 
- replaceReducer(nextReducer)
 
import { createStore } from 'redux';
let { subscribe, dispatch, getState } = createStore(reducer);
createStore方法还可以接受第二个参数,表示 State 的最初状态。这通常是服务器给出的。
 
let store = createStore(todoApp, window.STATE_FROM_SERVER)
上面代码中,window.STATE_FROM_SERVER就是整个应用的状态初始值。注意,如果提供了这个参数,它会覆盖 Reducer 函数的默认初始值。
 
下面是createStore方法的一个简单实现,可以了解一下 Store 是怎么生成的。
 
const createStore = (reducer) => {
  let state;
  let listeners = [];

  const getState = () => state;

  const dispatch = (action) => {
    state = reducer(state, action);
    listeners.forEach(listener => listener());
  };

  const subscribe = (listener) => {
    listeners.push(listener);
    return () => {
      listeners = listeners.filter(l => l !== listener);
    }
  };

  dispatch({});

  return { getState, dispatch, subscribe };};
 
 
五、Reducer 的拆分
Reducer 函数负责生成 State。由于整个应用只有一个 State 对象,包含所有数据,对于大型应用来说,这个 State 必然十分庞大,导致 Reducer 函数也十分庞大。
 
 
const chatReducer = (state = defaultState, action = {}) => {
  const { type, payload } = action;
  switch (type) {
    case ADD_CHAT:
      return Object.assign({}, state, {
        chatLog: state.chatLog.concat(payload)
      });
    case CHANGE_STATUS:
      return Object.assign({}, state, {
        statusMessage: payload
      });
    case CHANGE_USERNAME:
      return Object.assign({}, state, {
        userName: payload
      });
    default: return state;
  }};
 
上面代码中,三种 Action 分别改变 State 的三个属性。
 
- ADD_CHAT:chatLog属性
 
- CHANGE_STATUS:statusMessage属性
 
- CHANGE_USERNAME:userName属性
 
这三个属性之间没有联系,这提示我们可以把 Reducer 函数拆分。不同的函数负责处理不同属性,最终把它们合并成一个大的 Reducer 即可。
 
const chatReducer = (state = defaultState, action = {}) => {
  return {
    chatLog: chatLog(state.chatLog, action),
    statusMessage: statusMessage(state.statusMessage, action),
    userName: userName(state.userName, action)
  }};
 
上面代码中,Reducer 函数被拆成了三个小函数,每一个负责生成对应的属性。
这样一拆,Reducer 就易读易写多了。而且,这种拆分与 React 应用的结构相吻合:一个 React 根组件由很多子组件构成。这就是说,子组件与子 Reducer 完全可以对应。
Redux 提供了一个combineReducers方法,用于 Reducer 的拆分。你只要定义各个子 Reducer 函数,然后用这个方法,将它们合成一个大的 Reducer。
 
import { combineReducers } from 'redux';

const chatReducer = combineReducers({
  chatLog,
  statusMessage,
  userName
})

export default todoApp;
 
 
 
3.从简单 Flux/Redux 比较图可以看出两者之间有些差异:
 
React 和 Flux 之间的一些差异
React 只使用唯一的store 将整个应用的状态(state)用对象树(object tree)的方式储存起来
 
原生的Flux会有许多分散的state储存各个不同的状态。但是在redux中。只有唯一一个store将所有的资料用对象的方式包起来
 
 
//原生Flux的store
 
const userStore={
     name:""
}
const todoStore={
     text:""
}
 
//Redux中单一的store
 
const state={
     userState:{
          name:""
     },
     todoState:{
          text:''
     }
}
 
 
2.     唯一可以改变 state 的方法就是发送 action,这部份和 Flux 类似,但 Redux 并没有像 Flux 设计有 Dispatcher。Redux 的 action 和 Flux 的 action 都是一个包含 type 和 payload 的物件。
 
3.    Redux 拥有 Flux 所没有的 Reducer。Reducer 根据 action 的 type 去执行对应的 state 做变化的函式叫做 Reducer。你可以使用 switch 或是使用函式 mapping 的方式去对应处理的方式。
 
 
Redux 核心概念介绍
 

由于 Redux 官方也没有特别明确或严谨的规范。在一般情况我会将 reducers 分为 data 和单纯和 UI 有关的 ui state。但由于这边是比较简单的例子,我们最终只使用到 src/reducers/data/todoReducers.js

import { combineReducers } from 'redux-immutable';
import ui from './ui/uiReducers';// import routes from './routes';import todo from './data/todoReducers';// import routes from './routes';

const rootReducer = combineReducers({
  todo,
});

export default rootReducer;
原文地址:https://www.cnblogs.com/wy1935/p/7092875.html