第55节—— redux-toolkit中的createReducer——了解

一、概念

当我们使用 Redux 开发应用程序时,一个非常重要的概念就是 reducer。一个 reducer 是一个纯函数,它接受先前的状态和一个动作,然后返回一个新状态。每个动作都会引起状态的变化,从而使应用程序状态管理更加清晰和可控。

在 Redux Toolkit 中,createReducer 方法是一个用于创建 reducer 的简单工具,它可以将多个 reducer 函数组合成一个 reducer 函数,并使用更简洁的语法定义 reducer 函数。使用 createReducer 可以大大简化编写 reducer 函数的过程。

二、基本语法

1、基本语法

import { createReducer } from '@reduxjs/toolkit';
/* 最新版rtk已弃用 */
const initialState = { /* 初始状态 */ };
const myReducer = createReducer(initialState, {
  actionCreator1: (state, action) => { /* 处理 actionCreator1 */ },
  actionCreator2: (state, action) => { /* 处理 actionCreator2 */ },
  ...
});

2、使用一个带有多个 case 分支的 switch 语句来定义 reducer 函数

import { createReducer } from '@reduxjs/toolkit';

const initialState = { /* 初始状态 */ };
const myReducer = createReducer(initialState, (builder) => {
  builder
    .addCase(actionCreator1, (state, action) => { /* 处理 actionCreator1 */ })
    .addCase(actionCreator2, (state, action) => { /* 处理 actionCreator2 */ })
    ...
});

三、例子

1、创建counter-reducer.js文件

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;
  }
});

2、在store文件引入

import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './counterReducer';

const store = configureStore({
  reducer: counterReducer
});

3、页面中使用完成加、减、重置功能

import React from 'react';
import { useDispatch, useSelector } from 'react-redux';

const Counter = () => {
  const count = useSelector(state => state.count);
  const dispatch = useDispatch();

  return (
    <div>
      <h1>Count: {count}</h1>
      {/*
        dispatch方法中直接
        调用定义的reducer的方法
      */}
      <button onClick={() => dispatch({type: 'increment'})}>Increment</button>
      <button onClick={() => dispatch({type: 'decrement'})}>Decrement</button>
    </div>
  );
};

export default Counter;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值