[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;
相关文章
- React系列——websocket群聊系统在react的实现
- [React] Error boundary
- [React Typescript 2022] Use TypeScript to Type a React Class Component
- [React Testing] Create a Custom Render Function to Simplify Tests of Redux Components
- [React] Use CSS Transitions to Avoid a Flash of Loading State
- [React] Create a Persistent Reference to a Value Using React useRef Hook
- [React] Simplify and Convert a Traditional React Form to Formik
- [React + Functional Programming ADT] Create Redux Middleware to Dispatch Actions with the Async ADT
- [React] Refactor a connected Redux component to use Unstated
- [React] Refactor a Stateful List Component to a Functional Component with React PowerPlug
- [Recompose] Refactor React Render Props to Streaming Props with RxJS and Recompose
- [Recompose] Pass a React Prop to a Stream in RxJS
- [React Intl] Use Webpack to Conditionally Include an Intl Polyfill for Older Browsers
- [React] Intro to inline styles in React components
- [React] React Fundamentals: Introduction to Properties
- [React] useImperativeHandle, similar to Angular Directive `exportAs`
- [React] When to useReducer instead of useState
- [React + GraphQL] Use useLazyQuery to manually execute a query with Apollo React Hooks
- [PWA] Add Push Notifications to a PWA with React in Chrome and on Android
- [React] Use React.memo with a Function Component to get PureComponent Behavior
- [React] Refactor a connected Redux component to use Unstated
- [React] Use React Fragments to make your DOM tree cleaner
- [Recompose] Refactor React Render Props to Streaming Props with RxJS and Recompose
- [Recompose] Create Stream Behaviors to Push Props in React Components with mapPropsStream
- [React Intl] Get locale value from intl injector