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;
  • 相关阅读:
    防止表单重复提交
    tp5中的配置机制
    PHP remove,empty和detach区别
    jquery data方法
    webstrom使用记录
    input checkbox问题和li里面包含checkbox
    【转】HTML中A标签与click事件的前世今生
    jquery toggle方法
    webstore+nodejs
    web storm使用和配置
  • 原文地址:https://www.cnblogs.com/Answer1215/p/8547285.html
Copyright © 2011-2022 走看看