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>

  );

};
相关推荐
大怪v1 小时前
【搞发🌸活】不信书上那套理论!亲测Javascript能卡浏览器Reader一辈子~
javascript·html·浏览器
清羽_ls1 小时前
React Hooks 核心规则&自定义 Hooks
前端·react.js·hooks
西陵2 小时前
Nx带来极致的前端开发体验——任务缓存
前端·javascript·架构
Panda__Panda2 小时前
docker项目打包演示项目(数字排序服务)
运维·javascript·python·docker·容器·c#
10年前端老司机3 小时前
Promise 常见面试题(持续更新中)
前端·javascript
WebDesign_Mu5 小时前
为了庆祝2025英雄联盟全球总决赛开启,我用HTML+CSS+JS制作了LOL官方网站
javascript·css·html
噢,我明白了6 小时前
前端js 常见算法面试题目详解
前端·javascript·算法
学编程的小虎6 小时前
用 Python + Vue3 打造超炫酷音乐播放器:网易云歌单爬取 + Three.js 波形可视化
开发语言·javascript·python
做好一个小前端6 小时前
后端接口获取到csv格式内容并导出,拒绝乱码
前端·javascript·html
mapbar_front7 小时前
react项目开发—关于代码架构/规范探讨
前端·react.js