redux學習總結javascript
主要是學習完,爲了加深印象,整理的一些概念和總結,主要是參考阮大師的文章。css
<Provider store={store}>
引入。由於provider,是連接react和redux的,全部import { Provider } from 'react-redux';
import {createStore,applyMiddleware} from 'redux'
。createStore函數接受另外一個函數做爲參數,返回新生成的 Store 對象。dispactch,支持異步請求。java
import {createStore,applyMiddleware} from 'redux' import thunkMiddleware from 'redux-thunk' const createStoreWithMiddleware = applyMiddleware(thunkMiddleware)(createStore);
上面代碼使用redux-thunk中間件,改造store.dispatch,使得後者能夠接受函數做爲參數。
所以,異步操做的第一種解決方案就是,寫出一個返回函數的 Action Creator,而後使用redux-thunk中間件改造store.dispatch。react
建立一個action,簡化作法是createActionweb
import { createAction } from 'redux-actions'; import * as types from '../constants/ActionTypes'; const test = createAction(types.TEST);
Store 收到 Action 之後,必須給出一個新的 State,這樣 View 纔會發生變化。這種 State 的計算過程就叫作 Reducer。Reducer 是一個函數,它接受 Action 和當前 State 做爲參數,返回一個新的 State。redux
import { createStore } from 'redux'; const store = createStore(reducer);
createStore方法還能夠接受第二個參數,表示 State 的最初狀態。這一般是服務器給出的。數組
let store = createStore(reducer, window.STATE_FROM_SERVER)
上面代碼中,window.STATEFROMSERVER就是整個應用的狀態初始值。注意,若是提供了這個參數,它會覆蓋 Reducer 函數的默認初始值。服務器
function reducer(state, action) { return Object.assign({}, state, { thingToChange }); // 或者 return { ...state, ...newState }; } // State 是一個數組 function reducer(state, action) { return [...state, newItem]; }
import { handleActions } from 'redux-actions';
import * as types from '../constants/ActionTypes'; const initialState = { }; export default handleActions({ [types.SELECT_LUGGAGE] (state,action){ return { ...state } }, [types.SELECTED_LUGGAGE] (state,action){ var index = action.payload; return { ...state } } },initialState);
import { combineReducers } from 'redux';
import { combineReducers } from 'redux'; const chatReducer = combineReducers({ chatLog, statusMessage, userName }) export default todoApp;
上面的代碼經過combineReducers方法將三個子 Reducer 合併成一個大的函數。
這種寫法有一個前提,就是 State 的屬性名必須與子 Reducer 同名app
React-Redux 將全部組件分紅兩大類:UI 組件(presentational component)和容器組件(container component)。UI 組件負責 UI 的呈現,容器組件負責管理數據和邏輯。
你可能會問,若是一個組件既有 UI 又有業務邏輯,那怎麼辦?回答是,將它拆分紅下面的結構:外面是一個容器組件,裏面包了一個UI 組件。前者負責與外部的通訊,將數據傳給後者,由後者渲染出視圖。
React-Redux 規定,全部的 UI 組件都由用戶提供,容器組件則是由 React-Redux 自動生成。也就是說,用戶負責視覺層,狀態管理則是所有交給它。異步
React-Redux 提供connect方法,用於從 UI 組件生成容器組件。
~~~
import { connect } from 'react-redux'
const VisibleTodoList = connect( mapStateToProps, mapDispatchToProps )(TodoList) ~~~ 上面代碼中,connect方法接受兩個參數:mapStateToProps和mapDispatchToProps。它們定義了 UI 組件的業務邏輯。前者負責輸入邏輯,即將state映射到 UI 組件的參數(props),後者負責輸出邏輯,即將用戶對 UI 組件的操做映射成 Action。