Redux

作者: liwenliang | 来源:发表于2017-01-23 09:09 被阅读0次

将应用中所有的动作与状态都统一管理,让一切有据可循。

Redux的基本要素

  • State - 是应用的状态,一般本质上是一个普通对象
    若要改变 state,必须 dispatch 一个 action,这是修改应用状态的不二法门。

  • Store - 是应用状态 state 的管理者,包含下列四个函数:

getState() # 获取整个 state
dispatch(action) # ※ 触发 state 改变的【唯一途径】※
subscribe(listener) # 您可以理解成是 DOM 中的 addEventListener
replaceReducer(nextReducer) # 一般在 Webpack Code-Splitting 按需加载的时候用
  • Action - {type, payload} , type 表示请求的 URL,payload 表示请求的数据
  • Reducer - 本质上是根据 action.type 来更新 state 并返回 nextState 的函数
Redux 并不一定要搭配 React 使用。Redux 纯粹只是一个状态管理库,几乎可以搭配任何框架使用。
<!DOCTYPE html>
<html>
<head>
  <script src="//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) {
  // 首次调用本函数时设置初始 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; // 无论如何都返回一个 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>  ```

相关文章

网友评论

      本文标题:Redux

      本文链接:https://www.haomeiwen.com/subject/cirobttx.html