当前位置:网站首页>useReducer基本用法
useReducer基本用法
2022-04-23 06:05:00 【念雅】
一、引入api
import React ,{useReducer}from 'react';
二、基本使用
设置数值count,默认初始值为0,
传入不同分发方式,‘add’,‘sub’,
根据action不同,返回不同数值。
function UseReducerDemo() {
const [count, dispatch]=useReducer((state,action)=>{
switch (action) {
case 'add':
return state+1;
case 'sub':
return state-1;
default:
return state;
}
},0)
return<div>
<h2>现在的分数值是:{count}分</h2>
<button style={
{marginRight:10}} onClick={()=>{dispatch('add')}}>加分</button>
<button onClick={()=>{dispatch('sub')}}>减分</button>
</div>
}
export default UseReducerDemo
三、效果图

例子完结。
四、其他相关用法
第二个参数接收值,也接受{}对象,eg:
const initialState = {count: 0};
const [state, dispatch] = useReducer(reducer, initialState);
也可以这样用
function init(initialCount) {
return {count: initialCount};
}
function reducer(state, action) {
switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
case 'reset':
return init(action.payload);
default:
throw new Error();
}
}
function Counter({initialCount}) {
const [state, dispatch] = useReducer(reducer, initialCount, init);
return (
<>
Count: {state.count}
<button
onClick={() => dispatch({type: 'reset', payload: initialCount})}>
Reset
</button>
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
<button onClick={() => dispatch({type: 'increment'})}>+</button>
</>
);
版权声明
本文为[念雅]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_43865681/article/details/120418020
边栏推荐
猜你喜欢

Introduction to common APIs for EBFP programming

Implementation of multi tenant read and write in Prometheus cortex

mysql和pgsql时间相关操作

冬季实战营 动手实战-初识上云基础,动手实操ECS云服务器新手上路 领鼠标 云小宝 背包 无影

Introduction to DDoS attack / defense

基于ECS搭建云上博客(云小宝码上送祝福,免费抽iphone13任务详解)

try catch 不能捕获异步错误

窗口分析函数LAST_VALUE,FIRST_VALUE,lag,lead

Dolphinscheduler源码包src.tar.gz解压问题

Using Prom label proxy to implement label based multi tenant reading of Prometheus thanos
随机推荐
Alertmanager重复/缺失告警现象探究及两个关键参数group_wait和group_interval的释义
How does thanos configure different data retention durations for different tenants
TC ebpf practice
Static interface method calls are not supported at language level ‘5‘ 异常解决
OVS and OVS + dpdk architecture analysis
oracle表空间表分区详解及oracle表分区查询使用方法
ACFS文件系统创建扩大缩小等配置步骤
Django::Did you install mysqlclient?
Exception record-9
RAC环境alert日志报错Drop transient type: SYSTP2JW0acnAurDgU1sBqMBryw==的排查
qs. In the stringify interface, the input parameter is converted into a & connected string (with the application / x-www-form-urlencoded request header)
Dolphinscheduler源码包src.tar.gz解压问题
Try catch cannot catch asynchronous errors
OSS云存储管理实践(体验有礼)
Dolphinscheduler调度sql任务建表时The query did not generate a result set异常解决
冬季实战营动手实战-上云必备环境准备,动手实操快速搭建LAMP环境 领鼠标 云小宝 背包 无影
Prometheus监控influxdb的方法及指标释义
oracle清除sql的缓存
Build a cloud blog based on ECS (polite experience)
基於ECS搭建雲上博客(雲小寶碼上送祝福,免費抽iphone13任務詳解)