Redux介紹

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


Paste_Image.png

Action

Action用來(lái)傳遞操作state的信息到store,是store的唯一來(lái)源。以對(duì)象形式存在

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

多數(shù)情況下,type會(huì)被定義成字符串常量。且當(dāng)應(yīng)用規(guī)模較大時(shí),建議使用單獨(dú)的模塊或文件來(lái)存放 action。

隨著代碼的增多,這種直接聲明方式會(huì)難以組織,可以通過(guò)Action創(chuàng)建函數(shù)(Action Creator)來(lái)生產(chǎn)action

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

Reducer

Reducer用來(lái)處理action,通過(guò)傳入舊的state和action來(lái)指明如何更新state。

state 默認(rèn)情況下要返回應(yīng)用的初始 state,而且當(dāng)action.type很多時(shí),reducer也可以拆分成一個(gè)個(gè)小的reducer,每個(gè)reducer分別處理state中的一部分?jǐn)?shù)據(jù),最后將處理后的數(shù)據(jù)合并成整個(gè)state。其中,redux提供了combineReducers()方法來(lái)合并多個(gè)子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用來(lái)描述發(fā)發(fā)生了什么,reducer根據(jù)action更新state,Store就是把這幾樣?xùn)|西連接到一起的對(duì)象。
有以下職責(zé):
1、維持應(yīng)用的state
2、提供getState()方法獲取state
3、提供dispatch()方法更新state
4、通過(guò)subscribe()注冊(cè)監(jiān)聽(tīng)器
5、通過(guò)subscribe()返回的函數(shù)注銷監(jiān)聽(tīng)器

Redux 應(yīng)用只有一個(gè)單一的 store。

import { createStore } from 'redux'
import todoApp from './reducers'
//已有的 reducer 來(lái)創(chuàng)建 store
let store = createStore(todoApp,window.STATE_FROM_SERVER)//第二個(gè)參數(shù)用于設(shè)置state初始狀態(tài)。

最常用的是dispatch()方法,這是修改state的唯一途徑。Redux 中只需把 action 創(chuàng)建函數(shù)的結(jié)果傳給 dispatch()方法即可發(fā)起一次 dispatch 過(guò)程(這個(gè)過(guò)程就執(zhí)行了當(dāng)前的reducer)。

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

或者創(chuàng)建一個(gè) 被綁定的 action 創(chuàng)建函數(shù) 來(lái)自動(dòng) dispatch:

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

然后直接調(diào)用它們:

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中到底數(shù)據(jù)怎么傳遞呢?組件一級(jí)級(jí)的怎么通信呢?

react-redux

這用來(lái)結(jié)合react和redux,并提供了兩個(gè)接口Provider()和connect().

Provider可以將從createStore返回的store放入context中,使子集可以獲取到store并進(jìn)行操作;

//將根組件包裝進(jìn)Provider
let store = createStore(todoApp);
let rootElement = document.getElementById('root')
render(
  <Provider store={store}> 
        <App /> 
  </Provider>, 
  rootElement
)

connect 會(huì)把State和dispatch轉(zhuǎn)換成props傳遞給子組件, 是React與Redux連接的核心。
任何一個(gè)從 connect()包裝好的組件都可以得到一個(gè)dispatch()方法作為組件的 props,以及得到全局 state 中所需的任何內(nèi)容。connect()的唯一參數(shù)是 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() {
        // 通過(guò)調(diào)用 connect() 注入dispatch()方法和兩個(gè)組件分別所需要的state
        const { dispatch, visibleTodos, visibilityFilter } = this.props
        return ( 
            < div >
                < AddTodo onAddClick = {//onAddClick是在AddToDo組件中定義的從prop繼承的屬性方法dispatch()
                    text => dispatch(addTodo(text))//向dispatch()方法傳入action,直接更新對(duì)應(yīng)的state
                }
                />  
                < TodoList todos = { visibleTodos }//向該組件傳遞state
                onTodoClick = { index => dispatch(completeTodo(index)) }
                / > 
                < Footer filter = { visibilityFilter }
                onFilterChange = { nextFilter => dispatch(setVisibilityFilter(nextFilter)) }
                /> 
            </div > 
        )
    }
}
//提供驗(yàn)證器,來(lái)驗(yàn)證傳入數(shù)據(jù)的有效性
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 }
//根據(jù)用戶選擇,從而傳入相對(duì)應(yīng)的數(shù)據(jù)
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 到其默認(rèn)的 connect(select)(App) 中;
export default connect(select)(App);

【參考】

chrome擴(kuò)展Redux Devtools
http://www.itdecent.cn/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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容