Redux中文文檔:
Redux 入門教程(一):基本用法:
http://www.ruanyifeng.com/blog/2016/09/redux_tutorial_part_one_basic_usages.html
Redux 入門教程(二):中間件與異步操作:
http://www.ruanyifeng.com/blog/2016/09/redux_tutorial_part_two_async_operations.html
Redux 入門教程(三):React-Redux 的用法:
http://www.ruanyifeng.com/blog/2016/09/redux_tutorial_part_three_react-redux.html
redux工作流程
redux的工作流程可以大致總結(jié)為如下過程:
state-->actionCreator-->reducer-->combineReducers-->createStore-->bindActionCreators-->connect(mapStateToProps, mapDispatchToProps)(SomeComponent)
- 設(shè)計(jì)全局 state 的數(shù)據(jù)結(jié)構(gòu) ;
const ACTION_NAME= 'ACTION_NAME'
{
type: ACTION_NAME,
text: 'Your data'
}
- 設(shè)計(jì)更改 state 數(shù)據(jù)的 actionTypes 常量,以及其他跟視圖展現(xiàn)相關(guān)的 actionTypes 常量;
上步驟中ACTION_NAME即是actionTypes常量
const ACTION_NAME= 'ACTION_NAME'
- 根據(jù) actionTypes 常量,編寫 actionCreator函數(shù);
function doSomeAction(text) {
return {
type: ACTION_NAME,
text
}
}
- 根據(jù)各個(gè) actionCreator 的返回值,設(shè)計(jì) reducer 函數(shù)處理action傳入的數(shù)據(jù);
function doSomeThing(state = initialState, action) {
switch (action.type) {
case ACTION_NAME:
return Object.assign({}, state, {
text: action.text
})
default:
return state
}
}
- 在編寫完了所有 reducer 函數(shù)之后,createStore(reducer, initState) 得到全局 store 對象,并通過Provider傳遞給根組件;
import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import doSomeThing from './reducers'
import App from './components/App' //一般為根組件(本文件)之后的主頁面
let store = createStore(doSomeThing)
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
- 在需要使用redux的容器組件中,用 bindActionCreators 函數(shù)將 actionCreators 和 store.dispatch 綁定起來,得到一組能修改全局狀態(tài)的函數(shù) ;
bindActionCreators(actions, dispatch)
- 在需要使用redux的容器組件中,分發(fā)各個(gè)狀態(tài)和狀態(tài)修改函數(shù)到各個(gè) 頁面屬性和DOM 事件中:
function mapStateToProps (state) {
let {a, b, c} = state
return {a,b,c}
}
function mapDispatchToProps (dispatch) {
return bindActionCreators(actions, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps)(SomeComponent)