將應(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> ```