[React] How to use a setState Updater Function with a Reducer Pattern

In this lesson we'll walk through setting up an updater function that can receive an action argument. We'll also dive into how to separate your state management logic into a separate reducer function much like how Redux operates. It will receive an action which we can add any data and update state accordingly.

 

复制代码
import React, { Component } from "react";

const INCREMENT = "INCREMENT";
const DECREMENT = "DECREMENT";

const reducer = action => (state, props) => {
  switch (action.type) {
    case INCREMENT:
      return {
        value: state.value + action.amount,
      };
    case DECREMENT:
      return {
        value: state.value - 1,
      };
    default:
      return null;
  }
};

class App extends Component {
  state = {
    value: 0,
  };
  increment = () => {
    this.setState(
      reducer({
        type: INCREMENT,
        amount: 2
      }),
    );
  };
  decrement = () => {
    this.setState(
      reducer({
        type: DECREMENT,
      }),
    );
  };
  render() {
    return (
      <div>
        <div>{this.state.value}</div>
        <button onClick={this.increment}>Increment</button>
        <button onClick={this.decrement}>Decrement</button>
      </div>
    );
  }
}

export default App;
复制代码

 

posted @   Zhentiw  阅读(161)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2017-03-12 [Recompose] When nesting affects Style
2016-03-12 [RxJS] Refactoring CombineLatest to WithLatestFrom
点击右上角即可分享
微信分享提示