Redux 是一个用于 JavaScript 应用程序的状态管理库,它可以帮助开发者更高效地管理应用的状态。下面是一些关于 Redux 的基础知识。
安装 Redux
首先,你需要安装 Redux。你可以使用 npm 或 yarn 来安装它。
npm install redux
yarn add redux
Redux 的核心概念
- Action: Action 是一个描述发生了什么的普通对象。
- Reducer: Reducer 是一个函数,它接受当前的 state 和一个 action,然后返回新的 state。
- Store: Store 是一个对象,它保存了整个应用的状态,并提供了
getState()
、dispatch()
和subscribe()
等方法。
示例
假设我们有一个简单的计数器应用,它的 state 是一个数字。
// Action
const increment = { type: 'INCREMENT' };
const decrement = { type: 'DECREMENT' };
// Reducer
const counterReducer = (state = 0, action) => {
switch (action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
default:
return state;
}
};
// Store
const store = Redux.createStore(counterReducer);
// 订阅 store 的变化
store.subscribe(() => {
console.log(store.getState());
});
// 派发 action
store.dispatch(increment); // 输出 1
store.dispatch(decrement); // 输出 0
更多关于 Redux 的内容,可以查看我们的 Redux 教程。
图片
Redux 的核心概念可以通过以下图片来理解:
希望这能帮助你更好地理解 Redux!