首页 > web前端 > js教程 > 正文

React 基础知识~useReducer/ countup

Susan Sarandon
发布: 2024-10-13 18:22:29
原创
919 人浏览过
  • useReducer 是一个控制组件状态的 React hook。

  • 这个钩子经常用来控制输入值。

  • 这个hook的特点是,与useSate不同,它预先决定了如何更新状态。

・src/Example.js

import { useReducer } from "react";

const reducer = (prev, { type, step }) => {
  switch (type) {
    case "+":
      return prev + step;
    case "-":
      return prev - step;
    default:
      throw new Error("Invalid action");
  }
};

const Example = () => {
  const [state, dispatch] = useReducer(reducer, 0);

  const countup = () => {
    dispatch({ type: "+", step: 2 });
  };

  const countdown = () => {
    dispatch({ type: "-", step: 3 });
  };

  return (
    <>
      <h3>{state}</h3>
      <button onClick={countup}>+</button>
      <button onClick={countdown}>-</button>
    </>
  );
};

export default Example;

登录后复制
  • `reducer' 函数更新状态,例如使用开关功能。

  • 我们使用“dispatch”函数传递类型、步骤等对象参数。

・计数动作。

React Basics~useReducer/ countup

・倒计时的动作。

React Basics~useReducer/ countup

以上是React 基础知识~useReducer/ countup的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!