React中useReducer的理解与使用

这里以简单的语言描述一下useReducer的使用。也可自己查看官方文档(英文)

useReducer的使用场景:
当一个state需要维护多个数据且它们之间互相依赖。
这样业务代码中只需要通过dispatch来更新state,繁杂的逻辑都在reducer函数中了。

一、useReducer

demo:

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

1. useReducer

主要作用就是更新state。

参数:

  1. 第一个是 reducer 函数,这个函数返回一个新的state。
    后面再详述该函数的使用。
  2. 第二个是 state 初始值。

返回值:

  1. 当前 state。(可以在业务代码中获取、操作的就是它。)
  2. dispatch 函数,纯函数,用来更新state,并会触发re-render。
    (通俗地说,dispatch就是重新操作state的,会让组件重新渲染)

2. reducer函数

作用:处理传入的state,并返回新的state。

参数:

  1. 接受当前 state。
  2. 接受一个action,它是 dispatch 传入的。

返回值:

新的state。

3. dispatch函数

发送一个对象给reducer,即action。

参数: 一个对象。
返回值: 无。


完整代码:

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>
    </>
  );
}

猜你喜欢

转载自blog.csdn.net/aaqingying/article/details/127688428
今日推荐