[React] How to use a setState Updater Function with a Reducer Pattern
React to with How Function use pattern setState
2023-09-14 08:59:17 时间
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面试题总结
- React报错之Style prop value must be an object
- 腾讯前端二面react面试题合集
- 2022前端二面react面试题
- React Error: Failed at the xxx@0.1.0 start script 'react-scripts start'.
- react源码中的生命周期和事件系统
- React源码分析5-commit
- to program_I Just Want To
- 前端聊天功能如何实现_react使用websocket
- 深入react源码看setState究竟做了什么?
- 从源码角度看React-Hydrate原理_2023-03-01
- React源码中的计算流程和优先级
- react源码分析--深度理解React.Context
- React 18 componentDidMount重复执行两次的解决方案
- 常见react面试题(持续更新中)
- React 新提案 useEvent 已死
- React源码学习进阶(二)初识Fiber架构
- 在React中使用 react-router-dom 编程式路由导航【含V5.x、V6.x】
- react的jsx和React.createElement是什么关系?面试常问5
- React--15:生命周期新版本
- React和Vue谁会淘汰谁?
- Antd (react)风格表单开发最快方案
- 2021 年你应该尝试的 8 个 React 库
- Create React App 创建前端项目
- ECC TO HANA FAGLB03 search-help on Account Number field doesn’t working or not returning the selected value to the Account Number field.详解编程语言
- React 许可证虽严苛,但不必过度 react