当我们使用 Redux 开发应用程序时,一个非常重要的概念就是 reducer。一个 reducer 是一个纯函数,它接受先前的状态和一个动作,然后返回一个新状态。每个动作都会引起状态的变化,从而使应用程序状态管理更加清晰和可控。
在 Redux Toolkit 中,createReducer 方法是一个用于创建 reducer 的简单工具,它可以将多个 reducer 函数组合成一个 reducer 函数,并使用更简洁的语法定义 reducer 函数。使用 createReducer 可以大大简化编写 reducer 函数的过程。
import { createReducer } from '@reduxjs/toolkit';
/* 最新版rtk已弃用 */
const initialState = { /* 初始状态 */ };
const myReducer = createReducer(initialState, {
actionCreator1: (state, action) => { /* 处理 actionCreator1 */ },
actionCreator2: (state, action) => { /* 处理 actionCreator2 */ },
...
});
import { createReducer } from '@reduxjs/toolkit';
const initialState = { /* 初始状态 */ };
const myReducer = createReducer(initialState, (builder) => {
builder
.addCase(actionCreator1, (state, action) => { /* 处理 actionCreator1 */ })
.addCase(actionCreator2, (state, action) => { /* 处理 actionCreator2 */ })
...
});
const initialState = {
// 初始状态
count: 0
};
// 使用createReducer创建Reducer函数
const counterReducer = createReducer(initialState, {
// 处理increment action
increment: (state) => {
state.count += 1;
},
// 处理decrement action
decrement: (state) => {
state.count -= 1;
},
// 处理reset action
reset: (state) => {
state.count = 0;
}
});
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './counterReducer';
const store = configureStore({
reducer: counterReducer
});
import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
const Counter = () => {
const count = useSelector(state => state.count);
const dispatch = useDispatch();
return (
Count: {count}
{/*
dispatch方法中直接
调用定义的reducer的方法
*/}
);
};
export default Counter;