Redux的使用步驟

redux,react-redux ,react-thunk
redux: {creatStore,applyMiddleware,bindActionCreators};
react-redux: {provider,connect};
react-thunk:thunk
 
web應用是一個狀態機,視圖與狀態一一對應;
全部的狀態保存在一個對象中;
Store保存數據的地方,是一個狀態的容器,整個應用只能有一個Store。
3.1 Store
3.2 state
3.3 Action:Action 描述當前發生的事情。改變 State 的惟一辦法,就是使用 Action。它會運送數據到                      Store。
3.4 Action creator :View 要發送多少種消息,就會有多少種 Action。若是都手寫,會很麻煩。能夠定義一個函數來生成 Action,這個函數就叫 Action Creator。
      const ADD_TODO = ‘添加toDo'
    function addToDo(text) {
        return {
            todo: ADD_TODO,
            text
        }
    }
   const action = addToDo(‘learning redux’);//addToDo就是ActionCreator
3.5 store.dispatch(): store.dispatch()是 View 發出 Action 的惟一方法。
    import React from ‘react’;
    import React-dom from ‘react-dom’;
    import {createStore} from ‘redux’;
    const store = ctreateStore(fn);
    store.dispatch({
        type: ‘ADD_TODO’,
        payLoad: ‘learning English'
    })
or.
     store.dispatch(addToDo(‘learning hello’);
 
3.6 Reducer

Store 收到 Action 之後,必須給出一個新的 State,這樣 View 纔會發生變化。這種 State 的計算過程就叫作 Reducer。react

Reducer 是一個函數,它接受 Action 和當前 State 做爲參數,返回一個新的 State。web

const reducer = function (state,action) {redux

    return new_state;服務器

}
app

const defaultState = 0; dom

const reducer = (state = defaultState,action)=> { ide

    switch(action.type) {函數

        case ADD_ToDo: spa

            return state+action.payload;code

        default: 

            return state;    

    }

}

const state = reducer(1,{

    type: ADD,

    payload:  ‘learning redux'

})

2、Store的實現
 getState(),dispatch,subscribe()
 import {createStore} from ‘redux’;
{getState,dispatch,subscribe} = createStore(reducer);
createStore方法還能夠接受第二個參數,表示 State 的最初狀態。這一般是服務器給出的。
 
let store = createStore(todoApp, window.STATE_FROM_SERVER)
 
3、reducer的分拆與合併
    import {combineReducer} from ‘redux’;
    合併三個子Reducer;
    chatReducer =combineReducer({
        chatLog,
        statusMsg,
        userInfo
    }) ;
 
    const reducer = combineReducer({
        a: doSomethingWithA,
        b: processb,
        c: c
    });
    等價於:
    const reducer = function(state = defaultState,action)=> {
        return {
            a: doSomethingWithA(state.a,action),
            b: processB(state.b,action),
            c: c(state.c,actioin)
        }
    }
總之, combineReducers()作的就是產生一個總體的 Reducer 函數。
一個模擬combineReducer的簡單的實現;
    const reducer = (nextState,key) => {
        nextStae[key] = reducers[key](state[key],action);
        return nextState;
    }
    const combineReducer = reducers => {
        return ( state={}, action) => {
            return Object.keys(reducers).reduce((nextState,key) =>{
                nextState[key] = reducers[key](state[key],action);
                return nextState;
            },{})
 
        })
 
}
 
 
 
 
Redux:
    creatStore:redux生成Store的方法;
    import {createStore} from ‘redux’;
    const store = createStore(reducer);
    const state = store.getState();
相關文章
相關標籤/搜索