Redux
介绍
- redux 是 React 最常用的集中状态管理工具,类似于 vue 中的 Pinia(Vuex),可以独立于框架运行,作用是通过集中管理的方式管理应用的状态。

使用步骤
- 定义一个 reducer 函数(根据当前想要做的修改返回一个新的状态)
- 使用 createStore 方法传入 reducer 函数,生成一个 store 实例对象
- 使用 store 实例的 subscribe 方法订阅数据的变化(数据一旦变化可以得到通知)
- 使用 store 实例的 dispatch 方法提交 action 对象,触发数据变化(告诉 reducer 你想怎么改数据)
- 使用 store 实例的 getState 方法获取最新的状态数据更新到视图中
管理数据流量梳理

- 为了职责清晰,数据流向明确,redux 把整个数据修改的流程分成了三个核心概念,分别是:state、action 和 reducer。
- state:一个对象,存放着我们管理的数据状态
- action:一个对象,用来描述你想怎么改数据
- reducer:一个函数,用来根据action描述生成一个新的state
示例(独立示范)
<button id="decrement">-</button>
<span id="count">0</span>
<button id="increment">+</button>
<script src="https://unpkg.com/redux@latest/dist/redux.min.js"></script>
<script>
// 1. 定义 reducer 函数
// 作用:根据不同的 action 对象,返回不同新的 state
function reducer(state = { count: 0 }, action) {
// 数据不可变:基于原始状态生成一个新的状态
if (action.type === 'increment') {
return { count: state.count + 1 };
}
if (action.type === 'decrement') {
return { count: state.count - 1 };
}
return state;
}
// 2. 使用 reducer 函数生成store实例
const store = Redux.createStore(reducer);
// 3. 通过 store 实例的subscribe 订阅数据变化
// 回调函数可以在每次state发生变化的时候自动执行
store.subscribe(() => {
console.log('state 变化了', store.getState());
document.getElementById('count').innerHTML = store.getState().count;
});
// 4. 通过 store 实例的dispatch函数提交action更改状态
const inBtn = document.getElementById('increment')
inBtn.addEventListener('click', () => {
// 增
store.dispatch({
type: 'increment'
})
})
const dBtn = document.getElementById('decrement')
dBtn.addEventListener('click', () => {
// 减
store.dispatch({
type: 'decrement'
})
})
// 5. 通过 store 实例的getState函数获取最新状态更新到视图中
</script>