首先,需要安装Redux库并导入所需的函数和常量:
// 安装Redux:npm install redux
import { createStore } from 'redux';
接下来,定义初始状态和动作类型:
// 初始状态
const initialState = {
count: 0,
};
// 动作类型
const INCREMENT = 'INCREMENT';
const DECREMENT = 'DECREMENT';
然后,创建一个Reducer函数来处理状态更新:
// Reducer函数
const counterReducer = (state = initialState, action) => {
switch (action.type) {
case INCREMENT:
return {
...state,
count: state.count + 1,
};
case DECREMENT:
return {
...state,
count: state.count - 1,
};
default:
return state;
}
};
接下来,创建Redux store,并将Reducer传递给它:
// 创建Redux store
const store = createStore(counterReducer);
现在,可以派发动作并更新状态:
// 派发动作
store.dispatch({ type: INCREMENT });
console.log(store.getState()); // 输出: { count: 1 }
store.dispatch({ type: DECREMENT });
console.log(store.getState()); // 输出: { count: 0 }
最后,可以订阅状态的变化并执行相应的操作:
// 订阅状态变化
const unsubscribe = store.subscribe(() => {
console.log('当前状态:', store.getState());
});
// 派发动作
store.dispatch({ type: INCREMENT }); // 输出: 当前状态: { count: 1 }
store.dispatch({ type: DECREMENT }); // 输出: 当前状态: { count: 0 }
// 取消订阅
unsubscribe();
以上示例展示了Redux的基本工作流程。通过定义初始状态、动作类型和Reducer函数,创建Redux store,并使用dispatch
方法派发动作来更新状态。通过getState
方法可以获取当前状态,并通过subscribe
方法订阅状态的变化。这样,Redux就可以管理应用程序的状态,并提供可预测和可控制的数据流。