Understanding and use of useReducer in React

Here is a description of the use in simple language useReducer. You can also view the official documentation yourself (English)

The usage scenario of useReducer:
When a state needs to maintain multiple data and they depend on each other.
In this way, the business code only needs to update the state through dispatch, and the complicated logic is in the reducer function.

一、useReduce

demo:

function reducer(state, action){
    
    
  //...
}
const [state, dispatch] = useReducer(reducer, {
    
     name: "qingying", age: 18 });

1. useReducer

The main function is to update the state.

parameter:

  1. The first is reducerthe function , which returns a new state.
    The use of this function will be described in detail later.
  2. The second is statethe initial value.

return value:

  1. currently state. (It is what can be obtained and manipulated in business code.)
  2. dispatchFunction, pure function, used to update state and trigger re-render.
    (In layman's terms, dispatch is to re-operate the state, which will make the component re-render)

2. reducer function

Function: process the incoming state and return a new state.

parameter:

  1. Accept the current state.
  2. Accept an action, which is passed in by dispatch.

return value:

new state.

3. dispatch function

Send an object to the reducer, the action.

Parameters: an object.
Return value: None.


Full code:

import {
    
     useReducer } from "react";
/* 当state需要维护多个数据且它们互相依赖时,推荐使用useReducer
组件内部只是写dispatch({...})
处理逻辑的在useReducer函数中。获取action传过来的值,进行逻辑操作
*/

// reducer计算并返回新的state
function reducer(state, action) {
    
    
  const {
    
     type, nextName } = action;
  switch (type) {
    
    
    case "ADD":
      return {
    
    
        ...state,
        age: state.age + 1
      };
    case "NAME":
      return {
    
    
        ...state,
        name: nextName
      };
  }
  throw Error("Unknown action: " + action.type);
}

export default function ReducerTest() {
    
    
  const [state, dispatch] = useReducer(reducer, {
    
     name: "qingying", age: 12 });
  function handleInputChange(e) {
    
    
    dispatch({
    
    
      type: "NAME",
      nextName: e.target.value
    });
  }
  function handleAdd() {
    
    
    dispatch({
    
    
      type: "ADD"
    });
  }
  const {
    
     name, age } = state;
  return (
    <>
      <input value={
    
    name} onChange={
    
    handleInputChange} />
      <br />
      <button onClick={
    
    handleAdd}>添加1</button>
      <p>
        Hello,{
    
    name}, your age is {
    
    age}
      </p>
    </>
  );
}

Guess you like

Origin blog.csdn.net/aaqingying/article/details/127688428