自学内容网 自学内容网

react 响应式变量定义

一、useState

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

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` 也可以接受函数。这个函数接收前一个状态作为参数。可以基于前一个状态来计算。

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

const increment = () => {

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

};

二、useReducer

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

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>

  );

};

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

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>

  );

};


原文地址:https://blog.csdn.net/weixin_64684095/article/details/144127191

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!