zl程序教程

您现在的位置是:首页 >  前端

当前栏目

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

React to with How Function use pattern setState
2023-09-14 09:00:50 时间

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;