zoukankan      html  css  js  c++  java
  • [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;
  • 相关阅读:
    IM 融云 之 初始化及登录
    IM 融云 之 安装cocoapods 安装 SDK
    github desktop 下载
    iOS 架构模式
    IM 融云 之 通讯能力库API
    IM 融云 之 开发基础概念
    IM 之 融云
    php获得文件的属性
    js模拟复制
    linux修改yum源
  • 原文地址:https://www.cnblogs.com/Answer1215/p/8547285.html
Copyright © 2011-2022 走看看