Redux

將應(yīng)用中所有的動(dòng)作與狀態(tài)都統(tǒng)一管理,讓一切有據(jù)可循。

Redux的基本要素

  • State - 是應(yīng)用的狀態(tài),一般本質(zhì)上是一個(gè)普通對(duì)象
    若要改變 state,必須 dispatch 一個(gè) action,這是修改應(yīng)用狀態(tài)的不二法門。

  • Store - 是應(yīng)用狀態(tài) state 的管理者,包含下列四個(gè)函數(shù):

getState() # 獲取整個(gè) state
dispatch(action) # ※ 觸發(fā) state 改變的【唯一途徑】※
subscribe(listener) # 您可以理解成是 DOM 中的 addEventListener
replaceReducer(nextReducer) # 一般在 Webpack Code-Splitting 按需加載的時(shí)候用
  • Action - {type, payload} , type 表示請(qǐng)求的 URL,payload 表示請(qǐng)求的數(shù)據(jù)
  • Reducer - 本質(zhì)上是根據(jù) action.type 來(lái)更新 state 并返回 nextState 的函數(shù)
Redux 并不一定要搭配 React 使用。Redux 純粹只是一個(gè)狀態(tài)管理庫(kù),幾乎可以搭配任何框架使用。
<!DOCTYPE html>
<html>
<head>
  <script src="http://cdn.bootcss.com/redux/3.5.2/redux.min.js"></script>
</head>
<body>
<script>
/** Action Creators */
function inc() {
  return { type: 'INCREMENT' };
}
function dec() {
  return { type: 'DECREMENT' };
}

function reducer(state, action) {
  // 首次調(diào)用本函數(shù)時(shí)設(shè)置初始 state
  state = state || { counter: 0 };

  switch (action.type) {
    case 'INCREMENT':
      return { counter: state.counter + 1 };
    case 'DECREMENT':
      return { counter: state.counter - 1 };
    default:
      return state; // 無(wú)論如何都返回一個(gè) state
  }
}

var store = Redux.createStore(reducer);

console.log( store.getState() ); // { counter: 0 }

store.dispatch(inc());
console.log( store.getState() ); // { counter: 1 }

store.dispatch(inc());
console.log( store.getState() ); // { counter: 2 }

store.dispatch(dec());
console.log( store.getState() ); // { counter: 1 }
</script>
</body>
</html>  ```
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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