這幾天被redux折騰的夠嗆,看了不少視頻,也看了不少資料。不少時候,感受好像頓悟了,但實際上只是理解了其中的一個小概念而已。真正去作項目的時候,仍是會卡殼。多是學CSS和Javascript時花的時間過久了,學redux的時候有點浮躁。還有就是redux內容實在是很多,所有都看都理解,好像沒什麼必要。不看吧,用的時候老是有點力不從心。因而,決定把這些資料按本身的理解寫成博客,方便本身回憶思路,也但願能幫助到須要的人html
redux專一於狀態管理,把全部的狀態都存在一個對象中。核心概念包括:store、state、action、reducerreact
【store】ios
store是保存數據的地方,redux提供createStore函數來生成 Store。函數參數是後面要介紹的reducergit
import { createStore } from 'redux' const store = createStore(reducer)
【state】github
state是store的某個時刻的快照,能夠經過store.getState()取得當前時刻的statenpm
const state = store.getState()
【action】json
action用來改變state。action是一個對象,其中的type屬性是必須的,其餘的屬性通常用來設置改變state須要的數據redux
const action = { type: 'ADD_ONE', num: 1 }
store.dispatch()是發出action的惟一方法axios
const action = { type: 'ADD_ONE', num: 1 } store.dispatch(action)
【reducer】app
reducer 是一個函數,它接受action和當前state做爲參數,返回一個新的state
import { createStore } from 'redux' const store = createStore(reducer)
const reducer = (state = 10, action) => { switch (action.type) { case 'ADD_ONE': return state + action.num; default: return state; } };
當store.dispatch發送過來一個新的action,store就會自動調用reducer,獲得新的state
多餘的概念再也不介紹,下面用上面介紹的這四個核心概念實現一個簡單的實例,將create-react-app中index.js文件內容更改以下,便可運行
//第一步,建立action const addOne = { type: 'ADD', num: 1 } const addTwo = { type: 'ADD', num: 2 } const square = { type: 'SQUARE' } //第二步,建立reducer let math = (state = 10, action) => { switch (action.type) { case ADD: return state + action.num case SQUARE: return state * state default: return state } } //第三步,建立store import { createStore } from 'redux' const store = createStore(math) //第四步,測試,經過dispatch發出action,並經過getState()取得當前state值 console.log(store.getState()) //默認值爲10 store.dispatch(addOne) //發起'+1'的action console.log(store.getState()) //當前值爲10+1=11 store.dispatch(square) //發起'乘方'的action console.log(store.getState()) //當前值爲11*11=121 store.dispatch(addTwo) //發起'+2'的action console.log(store.getState()) //當前值爲121+2=123
結果以下
下面對目錄結構進行劃分
一、通常地,將action.type設置爲常量,這樣在書寫錯誤時,會獲得報錯提示
// constants/ActionTypes.js export const ADD = 'ADD' export const SQUARE = 'SQUARE'
二、能夠將addOne對象和addTwo對象整合成add函數的形式
// action/math.js import { ADD, SQUARE } from '../constants/ActionTypes' export const add = num => ({ type: ADD, num }) export const square = { type: SQUARE }
三、根據action.type的分類來拆分reducer,最終經過combineReducers方法將拆分的reducer合併起來。上例中的action類型都是數字運算,無需拆分,只需進行以下變化
// reducer/math.js import { ADD, SQUARE } from '../constants/ActionTypes' const math = (state = 10, action) => { switch (action.type) { case ADD: return state + action.num case SQUARE: return state * state default: return state } }
export default math
// reducer/index.js import { combineReducers } from 'redux' import math from './math' const rootReducer = combineReducers({ math }) export default rootReducer
四、將store存儲到store/index.js文件中
// store/index.js import { createStore } from 'redux' import rootReducer from '../reducer' export default createStore(rootReducer)
五、最終,根路徑下的index.js內容以下所示
import store from './store' import {add, square} from './action/math' console.log(store.getState()) //默認值爲10 store.dispatch(add(1)) //發起'+1'的action console.log(store.getState()) //當前值爲10+1=11 store.dispatch(square) //發起'乘方'的action console.log(store.getState()) //當前值爲11*11=121 store.dispatch(add(2)) //發起'+2'的action console.log(store.getState()) //當前值爲121+2=123
最終目錄路徑以下所示
最終結果以下所示
前面的示例中,只是redux的狀態改變,下面利用UI層來創建view和state的聯繫,將根目錄下的index.js的內容更改以下
import store from './store' import React from 'react' import ReactDOM from 'react-dom' import { add, square } from './action/math' ReactDOM.render( <div store={store}> <p>{store.getState().math}</p> <input type="button" onClick={() => store.dispatch(add(1))} value="+1" /> <input type="button" onClick={() => store.dispatch(add(2))} value="+2" /> <input type="button" onClick={() => store.dispatch(square)} value="乘方" /> </div>, document.getElementById('root') )
雖然能夠顯示數字,可是點擊按鈕時,卻不能從新渲染頁面
【store.subscribe()】
接下來介紹store.subscribe()方法了,該方法用來設置監聽函數,一旦state發生變化,就自動執行這個函數。該方法的返回值是一個函數,調用這個函數能夠解除監聽
下面將示例代碼更改以下
import store from './store' import React from 'react' import ReactDOM from 'react-dom' import { add, square } from './action/math' const render = () => ReactDOM.render( <div store={store}> <p>{store.getState().math}</p> <input type="button" onClick={() => store.dispatch(add(1))} value="+1" /> <input type="button" onClick={() => store.dispatch(add(2))} value="+2" /> <input type="button" onClick={() => store.dispatch(square)} value="乘方" /> </div>, document.getElementById('root') ) render() store.subscribe(render)
代碼終於能夠正常運行了
redux默認只處理同步,對於API請求這樣的異步任務則無能爲力
接下來嘗試使用axios的get方法來請求下面這個API
https://jsonplaceholder.typicode.com/posts/2
獲取的數據以下
{ "userId": 1, "id": 2, "title": "qui est esse", "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla" }
而後,將其id值設置爲state.math的值
代碼修改以下
// constants/ActionTypes.js export const ADD = 'ADD' export const SQUARE = 'SQUARE' export const SET = 'SET' // action/math.js import { ADD, SQUARE, SET } from '../constants/ActionTypes' export const add = num => ({ type: ADD, num }) export const square = { type: SQUARE } export const setNum = num => ({type: SET,num}) // reduce/math.js import { ADD, SQUARE,SET } from '../constants/ActionTypes' const math = (state = 10, action) => { switch (action.type) { case ADD: return state + action.num case SQUARE: return state * state case SET: return action.num default: return state } } export default math // index.js import store from './store' import React from 'react' import ReactDOM from 'react-dom' import { add, square, setNum } from './action/math' import axios from 'axios' let uri = 'https://jsonplaceholder.typicode.com/posts/2' const render = () => ReactDOM.render( <div store={store}> <p>{store.getState().math}</p> <input type="button" onClick={() => {axios.get(uri).then(res => {store.dispatch(store.dispatch(setNum(res.data.id)))})}} value="設置Num" /> <input type="button" onClick={() => store.dispatch(add(1))} value="+1" /> <input type="button" onClick={() => store.dispatch(add(2))} value="+2" /> <input type="button" onClick={() => store.dispatch(square)} value="乘方" /> </div>, document.getElementById('root') ) render() store.subscribe(render)
效果以下
可是,雖然API是異步操做,但store.dispatch並非異步,而axios經過get方法請求回來數據後,store.dispatch在axios中的then方法中同步取得數據
【redux-thunk】
若是要使用真正的異步操做,即把axios方法封裝到store.dispatch中,須要使用redux-thunk中間件
首先,使用npm進行安裝
npm install --save redux-thunk
而後,使用applyMiddleware來使用thunk中間件
import { createStore, applyMiddleware } from 'redux' import thunk from 'redux-thunk' import rootReducer from '../reducer' export default createStore(rootReducer,applyMiddleware(thunk))
接着來定義setNum這個action creator,而後在index.js文件的DOM加載完成後就發出setNum
[注意]若是action是一個對象,則它就是一個action,若是action是一個函數,則它是一個action creator,即action製造器
修改的代碼以下
// action/math.js import { ADD, SQUARE, SET } from '../constants/ActionTypes' import axios from 'axios' const uri = 'https://jsonplaceholder.typicode.com/posts/2' export const add = num => ({ type: ADD, num }) export const square = { type: SQUARE } export const setNum = () => (dispatch, getState) => { return axios.get(uri).then(res => { dispatch({ type: SET, num: res.data.id }) }) } // index.js import store from './store' import React from 'react' import ReactDOM from 'react-dom' import { add, square, setNum } from './action/math' const render = () => ReactDOM.render( <div store={store}> <p>{store.getState().math}</p> <input type="button" onClick={() => store.dispatch(setNum())} value="設置Num" /> <input type="button" onClick={() => store.dispatch(add(1))} value="+1" /> <input type="button" onClick={() => store.dispatch(add(2))} value="+2" /> <input type="button" onClick={() => store.dispatch(square)} value="乘方" /> </div>, document.getElementById('root') ) render() store.subscribe(render)
效果以下
【提示信息】
若是作的更完備一點,應該把異步請求時的提示信息也加上。增長一個fetch的action,用於控制fetch過程的提示信息及顯示隱藏狀況
代碼更改以下
// action/fetch.js import { SET_FETCH_MESSAGE, HIDE_FETCH_MESSAGE } from '../constants/ActionTypes' export const startFetch = { type: SET_FETCH_MESSAGE,message: '開始發送異步請求' } export const successFetch = { type: SET_FETCH_MESSAGE, message: '成功接收數據' } export const failFetch = { type: SET_FETCH_MESSAGE, message: '接收數據失敗' } export const hideFetchMessage = { type: HIDE_FETCH_MESSAGE }
// action/math.js import { ADD, SQUARE, SET } from '../constants/ActionTypes' import { startFetch, successFetch, failFetch, hideFetchMessage } from './fetch' import axios from 'axios' const uri = 'https://jsonplaceholder.typicode.com/posts/2' export const add = num => ({ type: ADD, num }) export const square = { type: SQUARE } export const setNum = () => (dispatch, getState) => { dispatch(startFetch) setTimeout(() => { dispatch(hideFetchMessage) }, 500) return axios .get(uri) .then(res => { setTimeout(() => { dispatch(successFetch) setTimeout(() => { dispatch(hideFetchMessage) }, 500) dispatch({ type: SET, num: res.data.id }) }, 1000) }) .catch(err => { dispatch(failFetch) setTimeout(() => { dispatch(hideFetchMessage) }, 500) }) }
// constants/ActionTypes.js export const ADD = 'ADD' export const SQUARE = 'SQUARE' export const SET = 'SET' export const SET_FETCH_MESSAGE = 'SET_FETCH_MESSAGE' export const HIDE_FETCH_MESSAGE = 'HIDE_FETCH_MESSAGE'
// reduce/fetch.js import { SET_FETCH_MESSAGE,HIDE_FETCH_MESSAGE } from '../constants/ActionTypes' const initState = { message:'', isShow:false } const fetch = (state = initState, action) => { switch (action.type) { case SET_FETCH_MESSAGE: return {isShow: true, message: action.message} case HIDE_FETCH_MESSAGE: return { isShow: false, message: '' } default: return state } } export default fetch
// index.js import store from './store' import React from 'react' import ReactDOM from 'react-dom' import { add, square, setNum } from './action/math' const render = () => ReactDOM.render( <div store={store}> <p>{store.getState().math}</p> <input type="button" onClick={() => store.dispatch(setNum())} value="設置Num" /> <input type="button" onClick={() => store.dispatch(add(1))} value="+1" /> <input type="button" onClick={() => store.dispatch(add(2))} value="+2" /> <input type="button" onClick={() => store.dispatch(square)} value="乘方" /> {store.getState().fetch.isShow && <p>{store.getState().fetch.message}</p>} </div>, document.getElementById('root') ) render() store.subscribe(render)
效果以下
下面來介紹react-redux。前面的代碼中,咱們是經過store.subscribe()方法監控state狀態的變化來更新UI層的。而使用react-redux,可讓組件動態訂閱狀態樹。狀態樹一旦被修改,組件能自動刷新顯示最新數據
react-redux將全部組件分紅兩大類:展現組件和容器組件。展現組件只負責UI呈現,全部數據由參數props提供;容器組件則負責管理數據和業務邏輯,帶有內部狀態,可以使用redux的API。要使用react-redux,就要遵照它的組件拆分規範
【provider】
react-redux提供Provider組件,可讓容器組件默承認以拿到state,而不用當容器組件層級很深時,一級級將state傳下去
將index.js文件更改以下
// index.js import React from 'react' import ReactDOM from 'react-dom' import store from './store' import MathContainer from './container/MathContainer' import { Provider } from 'react-redux' ReactDOM.render( <Provider store={store}> <MathContainer /> </Provider>, document.getElementById('root') )
按照組件拆分規範,將原來index.js中相關代碼,分拆到container/MathContainer和component/Math這兩個組件中
【connect】
react-redux提供connect方法,用於從展現組件生成容器組件。connect的意思就是將這兩種組件鏈接起來
import { connect } from 'react-redux' const MathContainer = connect()(Math);
Math是展現組件,MathContainer就是由React-redux經過connect方法自動生成的容器組件
爲了定義業務邏輯,須要給出下面兩方面的信息
一、輸入邏輯:外部的數據(即state對象)如何轉換爲展現組件的參數
二、輸出邏輯:用戶發出的動做如何變爲Action對象,從展現組件傳出去
所以,connect方法的完整API以下
import {connect} from 'react-redux' const MathContainer= connect( mapStateToProps, mapDispatchToProps )(Math)
上面代碼中,connect方法接受兩個參數:mapStateToProps和mapDispatchToProps。它們定義了展現組件的業務邏輯。前者負責輸入邏輯,即將state映射到UI組件的參數(props),後者負責輸出邏輯,即將用戶對展現組件的操做映射成Action
【mapStateToProps()】
mapStateToProps創建一個從外部的state對象到展現組件的props對象的映射關係。做爲參數,mapStateToProps執行後應該返回一個對象,裏面的每個鍵值對就是一個映射。
const mapStateToProps = (state) => { return { num: getNum(state) } }
mapStateToProps的第一個參數老是state對象,還可使用第二個參數,表明容器組件的props對象。使用ownProps做爲參數後,若是容器組件的參數發生變化,也會引起展現組件從新渲染
const mapStateToProps = (state,ownProps) => { return { num: getNum(state) } }
mapStateToProps會訂閱Store,每當state更新的時候,就會自動執行,從新計算展現組件的參數,從而觸發展現組件的從新渲染。connect方法能夠省略mapStateToProps參數,那樣,展現組件就不會訂閱Store,就是說Store的更新不會引發展現組件的更新
【mapDispatchToProps】
mapDispatchToProps是connect函數的第二個參數,用來創建展現組件的參數到store.dispatch方法的映射。也就是說,它定義了用戶的哪些操做應該看成action,傳給Store。它能夠是一個函數,也能夠是一個對象
若是mapDispatchToProps是一個函數,會獲得dispatch和ownProps(容器組件的props對象)兩個參數
const mapDispatchToProps = (dispatch,ownProps) => { return { onSetNumClick: () => dispatch(setNum()) } }
mapDispatchToProps做爲函數,應該返回一個對象,該對象的每一個鍵值對都是一個映射,定義了展現組件的參數怎樣發出action
若是mapDispatchToProps是一個對象,它的每一個鍵名也是對應展現組件的同名參數,鍵值應該是一個函數,會被看成action creator,返回的action會由redux自動發出
所以,上面的寫法簡寫以下所示
const mapDispatchToProps = { onsetNumClick: () => setNum() }
因爲store目錄中,只能一個index.js文件,且不會有內容擴展,將其更改成根目錄下的store.js文件
將其餘的目錄都變成複數形式,最終的目錄結構以下所示
效果以下
詳細代碼以下所示,且可訪問github線上地址
【components】
// components/Math.js import React from 'react' const Math = ({ num, isShow, fetchMessage, onSetNumClick, onAddOneClick, onAddTwoClick, onSqureClick }) => ( <section> <p>{num}</p> <input type="button" onClick={onSetNumClick} value="設置Num" /> <input type="button" onClick={onAddOneClick} value="+1" /> <input type="button" onClick={onAddTwoClick} value="+2" /> <input type="button" onClick={onSqureClick} value="乘方" /> {isShow && <p>{fetchMessage}</p>} </section> ) export default Math
【containers】
// containers/MathContainer.js import { connect } from 'react-redux' import Math from '../components/Math' import { getNum } from '../selectors/math' import { getFetchMessage, getFetchIsShow } from '../selectors/fetch' import { setNum, add, square } from '../actions/math' const mapStateToProps = state => { return { num: getNum(state), fetchMessage: getFetchMessage(state), isShow: getFetchIsShow(state) } } const mapDispatchToProps = { onSetNumClick: () => setNum(), onAddOneClick: () => add(1), onAddTwoClick: () => add(2), onSqureClick: () => square } const MathContainer = connect(mapStateToProps, mapDispatchToProps)(Math) export default MathContainer
【actions】
// actions/fetch.js import { SET_FETCH_MESSAGE, HIDE_FETCH_MESSAGE } from '../constants/ActionTypes' export const startFetch = { type: SET_FETCH_MESSAGE,message: '開始發送異步請求' } export const successFetch = { type: SET_FETCH_MESSAGE, message: '成功接收數據' } export const failFetch = { type: SET_FETCH_MESSAGE, message: '接收數據失敗' } export const hideFetchMessage = { type: HIDE_FETCH_MESSAGE }
// actions/math.js import { ADD, SQUARE, SET } from '../constants/ActionTypes' import { startFetch, successFetch, failFetch, hideFetchMessage } from './fetch' import axios from 'axios' const uri = 'https://jsonplaceholder.typicode.com/posts/2' export const add = num => ({ type: ADD, num }) export const square = { type: SQUARE } export const setNum = () => (dispatch, getState) => { dispatch(startFetch) setTimeout(() => {dispatch(hideFetchMessage)}, 300) return axios .get(uri) .then(res => { dispatch(successFetch) setTimeout(() => {dispatch(hideFetchMessage)}, 300) dispatch({ type: SET, num: res.data.id }) }) .catch(err => { dispatch(failFetch) setTimeout(() => {dispatch(hideFetchMessage)}, 300) }) }
【constants】
// constants/ActionTypes.js export const ADD = 'ADD' export const SQUARE = 'SQUARE' export const SET = 'SET' export const SET_FETCH_MESSAGE = 'SET_FETCH_MESSAGE' export const HIDE_FETCH_MESSAGE = 'HIDE_FETCH_MESSAGE'
【reducers】
// reducers/fetch.js import { SET_FETCH_MESSAGE,HIDE_FETCH_MESSAGE } from '../constants/ActionTypes' const initState = { message:'', isShow:false } const fetch = (state = initState, action) => { switch (action.type) { case SET_FETCH_MESSAGE: return {isShow: true, message: action.message} case HIDE_FETCH_MESSAGE: return { isShow: false, message: '' } default: return state } } export default fetch
// reducers/index.js import { combineReducers } from 'redux' import math from './math' import fetch from './fetch' const rootReducer = combineReducers({ math, fetch }) export default rootReducer
// reduces/math.js import { ADD, SQUARE,SET } from '../constants/ActionTypes' const math = (state = 10, action) => { switch (action.type) { case ADD: return state + action.num case SQUARE: return state * state case SET: return action.num default: return state } } export default math
【selectors】
// selectors/fetch.js export const getFetchMessage = state => state.fetch.message export const getFetchIsShow = state => state.fetch.isShow
// selectors/math.js export const getNum = state => state.math
【根目錄】
// index.js import React from 'react' import ReactDOM from 'react-dom' import store from './store' import MathContainer from './containers/MathContainer' import { Provider } from 'react-redux' ReactDOM.render( <Provider store={store}> <MathContainer /> </Provider>, document.getElementById('root') )
// store.js import { createStore, applyMiddleware } from 'redux' import thunk from 'redux-thunk' import rootReducer from './reducers' export default createStore(rootReducer,applyMiddleware(thunk))