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>

  );

};
相关推荐
鹏多多16 分钟前
前端是如何死去的?| 完整时间线
前端·javascript·程序员
看浪的路人24 分钟前
第2讲:ReAct 模式从零实现——不用框架,手写一个 Agent 内核
前端·react.js·前端框架
古夕42 分钟前
iframe 授权失败时露出 60000 JSON 的复盘
前端·javascript
程序员Sunday1 小时前
ES Module 和 CommonJS 有什么区别?循环依赖时会发生什么?
前端·javascript·面试
有味道的男人2 小时前
搜好货平台关键词商品搜索接口:分页容错与商品数据轻量化提取方案
服务器·前端·javascript
雪雪爱冲浪5 小时前
JavaScript 网络爬虫教程(2026)
开发语言·javascript·爬虫
软件技术NINI5 小时前
化妆品html+css+js 7页
javascript·css·html
要吃这碗饭5 小时前
JavaScript 网络爬虫教程(2026)
开发语言·javascript·爬虫
lexiangqicheng5 小时前
自定义表单跨端共用机制-PC设计APP渲染
java·前端·javascript
沙漏无语5 小时前
pnpm 安装@vue-office包的幽灵依赖问题解决
前端·javascript·vue.js