react 响应式变量定义

一、useState

接受一个初始值作为参数,并返回一个包含两个元素的数组。

javascript 复制代码
import { useState } from "react";



const Counter = () => {

  const [count, setCount] = useState(0);

  return (

    <div>

      <p>Count: {count}</p>

      <button onClick={() => setCount(count + 1)}>Increment</button>

    </div>

  );

};

`setCount` 也可以接受函数。这个函数接收前一个状态作为参数。可以基于前一个状态来计算。

javascript 复制代码
const [count, setCount] = useState(0);

const increment = () => {

  setCount((prevCount) => prevCount + 1);

};

二、useReducer

接受一个`reducer`函数和一个初始状态作为参数。返回一个包含当前状态和`dispatch`函数的数组。

javascript 复制代码
import { useReducer } from "react";



const counterReducer = (state, action) => {

  switch (action.type) {

    case "INCREMENT":

      return state + 1;

    case "DECREMENT":

      return state - 1;

    default:

      return state;

  }

};

const Counter = () => {

  const [count, dispatch] = useReducer(counterReducer, 0);

  return (

    <div>

      <p>Count: {count}</p>

      <button onClick={() => dispatch({ type: "INCREMENT" })}>Increment</button>

      <button onClick={() => dispatch({ type: "DECREMENT" })}>Decrement</button>

    </div>

  );

};

假设一个组件用于管理一个表单的状态,包括输入框的值和表单是否提交的状态:

javascript 复制代码
const formReducer = (state, action) => {

  switch (action.type) {

    case "UPDATE_INPUT":

      return { ...state, inputValue: action.payload };

    case "SUBMIT_FORM":

      return { ...state, isSubmitted: true };

    default:

      return state;

  }

};

const FormComponent = () => {

  const [formState, dispatch] = useReducer(formReducer, {

    inputValue: "",

    isSubmitted: false,

  });

  const handleInputChange = (e) => {

    dispatch({ type: "UPDATE_INPUT", payload: e.target.value });

  };

  const handleSubmit = () => {

    dispatch({ type: "SUBMIT_FORM" });

  };

  return (

    <form onSubmit={handleSubmit}>

      <input

        type="text"

        value={formState.inputValue}

        onChange={handleInputChange}

      />

      {formState.isSubmitted && <p>Form submitted!</p>}

      <button type="submit">Submit</button>

    </form>

  );

};
相关推荐
默_笙7 分钟前
💫 闭包是个背包:拆解小米前端面试题里的三道"闭包陷阱"
前端·javascript·面试
尾善爱看海3 小时前
《JavaScript 数组操作全攻略:12 类 API + 30 个实战场景 + 20 个避坑指南》
前端·javascript·面试
OpsEye3 小时前
为什么你的 Agent 莫名烧钱?聊聊循环调用的兜底方案
javascript·ai编程
linux_cfan4 小时前
16 · `custom-media-element`:属性拦截与转发
前端·javascript·音视频
右耳朵猫AI4 小时前
Web前端周刊2026W38 | React 19.3 发布、StyleX 深潜、jsdom 30.1 提速
前端·javascript·react.js·typescript·node.js
落魄大学生之流水线上谋生计4 小时前
GreenLife Carbon · OpenHarmony 智慧低碳生态平台
javascript
福兮说5 小时前
用 IndexedDB 存用户的文件,我踩过的五个坑
前端·javascript
胡志辉的博客5 小时前
【完全开源】IP 纯净度检测 可一键部署到自己的CF
前端·javascript·chrome·ip·chromium
Hilaku6 小时前
作为面试官,我最怕遇到什么样的候选人?
前端·javascript·程序员
web3d5207 小时前
01-用 Leafletjs 10 分钟搭一张水利一张图(Vue3 + Vite 实战)
前端·javascript