7.Redux學(xué)習(xí)體會

Redux中文文檔:

http://www.redux.org.cn/

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)

  1. 設(shè)計(jì)全局 state 的數(shù)據(jù)結(jié)構(gòu) ;
const ACTION_NAME= 'ACTION_NAME'

{
  type: ACTION_NAME,
  text: 'Your data'
}
  1. 設(shè)計(jì)更改 state 數(shù)據(jù)的 actionTypes 常量,以及其他跟視圖展現(xiàn)相關(guān)的 actionTypes 常量;

上步驟中ACTION_NAME即是actionTypes常量

const ACTION_NAME= 'ACTION_NAME'
  1. 根據(jù) actionTypes 常量,編寫 actionCreator函數(shù);
function doSomeAction(text) {
  return {
    type: ACTION_NAME,
    text
  }
}
  1. 根據(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
  }
}
  1. 在編寫完了所有 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')
)
  1. 在需要使用redux的容器組件中,用 bindActionCreators 函數(shù)將 actionCreators 和 store.dispatch 綁定起來,得到一組能修改全局狀態(tài)的函數(shù) ;
bindActionCreators(actions, dispatch)
  1. 在需要使用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)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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