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>

  );

};
相关推荐
OEC小胖胖8 小时前
告别 undefined is not a function:TypeScript 前端开发优势与实践指南
前端·javascript·typescript·web
行云&流水8 小时前
Vue3 Lifecycle Hooks
前端·javascript·vue.js
老虎06278 小时前
JavaWeb(苍穹外卖)--学习笔记04(前端:HTML,CSS,JavaScript)
前端·javascript·css·笔记·学习·html
三水气象台9 小时前
用户中心Vue3网页开发(1.0版)
javascript·css·vue.js·typescript·前端框架·html·anti-design-vue
烛阴9 小时前
Babel 完全上手指南:从零开始解锁现代 JavaScript 开发的超能力!
前端·javascript
CN-Dust10 小时前
[FMZ][JS]第一个回测程序--让时间轴跑起来
javascript
全宝11 小时前
🎨前端实现文字渐变的三种方式
前端·javascript·css
yanlele11 小时前
前端面试第 75 期 - 2025.07.06 更新前端面试问题总结(12道题)
前端·javascript·面试
妮妮喔妮11 小时前
【无标题】
开发语言·前端·javascript
fie888911 小时前
浅谈几种js设计模式
开发语言·javascript·设计模式