当前位置:网站首页>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
边栏推荐
猜你喜欢
mysql和pgsql时间相关操作
High performance gateway for interconnection between VPC and IDC based on dpdk
Dolphinscheduler配置Datax踩坑记录
Winter combat camp hands-on combat - cloud essential environment preparation, hands-on practical operation, quickly build lamp environment, lead mouse cloud Xiaobao backpack without shadow
Typical application scenarios of alicloud log service SLS
Dolphinscheduler调度sql任务建表时The query did not generate a result set异常解决
PG SQL截取字符串到指定字符位置
Information:2021/9/29 10:01 - Build completed with 1 error and 0 warnings in 11s 30ms Error异常处理
专用窗口函数rank, dense_rank, row_number
基于ECS搭建云上博客(云小宝码上送祝福,免费抽iphone13任务详解)
随机推荐
异常记录-16
oracle杀死正在执行的sql
Research on alertmanager repeated / missing alarm phenomenon and two key parameters_ Wait and group_ Interpretation of interval
Thanos compact component test summary (processing historical data)
Introduction to RDMA network
Abnormal record-16
Redis FAQ
Thanos如何为不同租户配置不同的数据保留时长
Exception record-8
测试oracle库700万数据量普通方式创建索引所需时间
异常记录-18
异常记录-11
Build a cloud blog based on ECS (polite experience)
异常记录-12
Dolphinscheduler集成Flink任务踩坑记录
Abnormal record-15
Ali vector library Icon tutorial (online, download)
oracle存储过程中is和as区别
异常记录-19
双指针仪表盘读数(一)