Redux 介绍
JavaScript 状态容器,提供可预测化的状态管理。
容器:JavaScript 对象
状态:数据
Redux 核心概念及工作流程
- Store:存储状态的容器,JavaScript 对象
- View:视图,HTML页面
- Actions:对象,描述对状态进行怎样的操作
- Reducers:函数,操作状态并返回新的状态
Redux 计数器案例
<button id="plus">+</button>
<span id="count">0</span>
<button id="minus">-</button>
<script src="https://cdn.bootcss.com/redux/4.0.5/redux.min.js"></script>
<script>
// 3. 存储默认状态
const initialState = {
count: 0
};
// 2. 创建 reducer 函数
// 7. 第二个参数接受 action
function reducer (state = initialState, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
return state;
}
}
// 1. 创建 store 对象
const store = Redux.createStore(reducer);
// 4. 定义 action
const increment = { type: 'increment' };
const decrement = { type: 'decrement' };
// 5. 获取按钮 给按钮添加点击事件
document.getElementById('plus').onclick = function () {
// 6. 触发 action
store.dispatch(increment);
};
document.getElementById('minus').onclick = function () {
// 6. 触发 action
store.dispatch(decrement);
}
// 7. 订阅 store
store.subscribe(() => {
// 获取 store 对象中存储的状态
// console.log(store.getState());
document.getElementById('count').innerHTML = store.getState().count;
})
</script>
复制代码
Redux 核心 API
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END