Redux介绍

2016-05-22  本文已影响912人  RichardBillion

Redux中主要由三部分组成:Action,Reducer,Store.


Paste_Image.png

Action

Action用来传递操作state的信息到store,是store的唯一来源。以对象形式存在

{ 
  type: 'ADD_TODO',//type必须,其余字段随意。
   text: 'Build my first Redux app'
}

多数情况下,type会被定义成字符串常量。且当应用规模较大时,建议使用单独的模块或文件来存放 action。

随着代码的增多,这种直接声明方式会难以组织,可以通过Action创建函数(Action Creator)来生产action

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

Reducer

Reducer用来处理action,通过传入旧的state和action来指明如何更新state。

state 默认情况下要返回应用的初始 state,而且当action.type很多时,reducer也可以拆分成一个个小的reducer,每个reducer分别处理state中的一部分数据,最后将处理后的数据合并成整个state。其中,redux提供了combineReducers()方法来合并多个子reducer。

import { combineReducers } from 'redux'
import { ADD_TODO, TOGGLE_TODO, SET_VISIBILITY_FILTER, VisibilityFilters } from './actions'
const { SHOW_ALL } = VisibilityFilters
function visibilityFilter(state = SHOW_ALL, action) {
   switch (action.type) {
     case SET_VISIBILITY_FILTER: 
        return action.filter
       default: return state 
   }
}
function todos(state = [], action) { 
    switch (action.type) { 
        case ADD_TODO:
           return [ ...state, { text: action.text, completed: false } ]
       case TOGGLE_TODO: 
            return state.map((todo, index) => {
                 if (index === action.index) { 
                      return Object.assign({}, todo, { 
                            completed: !todo.completed 
                      })
                 }
                 return todo
           })
       default: return state
 }}
const todoApp = combineReducers({ visibilityFilter, todos})
export default todoApp

Store

action用来描述发发生了什么,reducer根据action更新state,Store就是把这几样东西连接到一起的对象。
有以下职责:
1、维持应用的state
2、提供getState()方法获取state
3、提供dispatch()方法更新state
4、通过subscribe()注册监听器
5、通过subscribe()返回的函数注销监听器

Redux 应用只有一个单一的 store

import { createStore } from 'redux'
import todoApp from './reducers'
//已有的 reducer 来创建 store
let store = createStore(todoApp,window.STATE_FROM_SERVER)//第二个参数用于设置state初始状态。

最常用的是dispatch()方法,这是修改state的唯一途径。Redux 中只需把 action 创建函数的结果传给 dispatch()方法即可发起一次 dispatch 过程(这个过程就执行了当前的reducer)。

dispatch(addTodo(text))
dispatch(completeTodo(index))

或者创建一个 被绑定的 action 创建函数 来自动 dispatch:

const boundAddTodo = (text) => dispatch(addTodo(text))
const boundCompleteTodo = (index) => dispatch(completeTodo(index))

然后直接调用它们:

boundAddTodo(text);
boundCompleteTodo(index);

下面是dispatch得部分源码

function dispatch(action) { 
   currentState = currentReducer(currentState, action);
   listeners.slice().forEach(function (listener) {
       return listener(); 
   });
    return action;
}

所以redux的具体流程图如下


redux flow

那么redux中到底数据怎么传递呢?组件一级级的怎么通信呢?

react-redux

这用来结合react和redux,并提供了两个接口Provider()和connect().

Provider可以将从createStore返回的store放入context中,使子集可以获取到store并进行操作;

//将根组件包装进Provider
let store = createStore(todoApp);
let rootElement = document.getElementById('root')
render(
  <Provider store={store}> 
        <App /> 
  </Provider>, 
  rootElement
)

connect 会把State和dispatch转换成props传递给子组件, 是React与Redux连接的核心。
任何一个从 connect()包装好的组件都可以得到一个dispatch()方法作为组件的 props,以及得到全局 state 中所需的任何内容。connect()的唯一参数是 selector。此方法可以从 Redux store 接收到全局的 state,然后返回组件中需要的 props。

import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { addTodo, completeTodo, setVisibilityFilter, VisibilityFilters } from '../actions';
import AddTodo from '../components/AddTodo';
import TodoList from '../components/TodoList';
import Footer from '../components/Footer';
class App extends Component {
    render() {
        // 通过调用 connect() 注入dispatch()方法和两个组件分别所需要的state
        const { dispatch, visibleTodos, visibilityFilter } = this.props
        return ( 
            < div >
                < AddTodo onAddClick = {//onAddClick是在AddToDo组件中定义的从prop继承的属性方法dispatch()
                    text => dispatch(addTodo(text))//向dispatch()方法传入action,直接更新对应的state
                }
                />  
                < TodoList todos = { visibleTodos }//向该组件传递state
                onTodoClick = { index => dispatch(completeTodo(index)) }
                / > 
                < Footer filter = { visibilityFilter }
                onFilterChange = { nextFilter => dispatch(setVisibilityFilter(nextFilter)) }
                /> 
            </div > 
        )
    }
}
//提供验证器,来验证传入数据的有效性
App.propTypes = { 
    visibleTodos: PropTypes.arrayOf(PropTypes.shape({ text: PropTypes.string.isRequired, completed: PropTypes.bool.isRequired })), 
    visibilityFilter: PropTypes.oneOf(['SHOW_ALL', 'SHOW_COMPLETED', 'SHOW_ACTIVE']).isRequired }
//根据用户选择,从而传入相对应的数据
function selectTodos(todos, filter) {
    switch (filter) {
        case VisibilityFilters.SHOW_ALL:
            return todos;
        case VisibilityFilters.SHOW_COMPLETED:
            return todos.filter(todo => todo.completed);
        case VisibilityFilters.SHOW_ACTIVE:
            return todos.filter(todo => !todo.completed);
    }
} 
// 基于全局 state ,哪些是我们想注入的 props ?// 注意:使用 https://github.com/faassen/reselect 效果更佳。
function select(state) {
  return {
    visibleTodos: selectTodos(state.todos, state.visibilityFilter),
    visibilityFilter: state.visibilityFilter
  };
}

// 包装 component ,注入 dispatch 和 state 到其默认的 connect(select)(App) 中;
export default connect(select)(App);

【参考】

chrome扩展Redux Devtools
http://www.jianshu.com/p/3334467e4b32
http://react-china.org/t/redux/2687
https://leozdgao.me/reacthe-reduxde-qiao-jie-react-redux/
https://github.com/matthew-sun/blog/issues/18
http://book.apebook.org/boyc/redux/redux2.html
http://hustlzp.com/post/2016/03/react-redux-deployment

上一篇 下一篇

猜你喜欢

热点阅读