Day 15 - 用 useReducer 取代 useState !?

如果有错误,欢迎留言指教~ Q_Q

上篇提到,如何取得更新後的 state

useReduceruseState 都是拿来管理 state 的 hook

一样都可以做到储存和变更 state 的功能,如下:

使用 useState

import { useState } from "react";

export default function App() {
  const [count, setCount] = useState(0);
  
  const handleIncrease = () => {
    setCount((prev) => prev + 1);
  };

  const handleDecrease = () => {
    setCount((prev) => prev - 1);
  };
  
  return (
    <div className="App">
      <button onClick={handleIncrease}>+</button>
      <h1>{count}</h1>
      <button onClick={handleDecrease}>-</button>
    </div>
  );
}

codeSandBox


使用 useReducer

import { useReducer } from "react";

const ACTIONS = {
  INCREMENT: "Increament",
  DECREMENT: "Decreament"
};

const reducer = (state, action) => {
  switch (action.type) {
    case ACTIONS.INCREMENT:
      return { count: state.count + 1 };
    case ACTIONS.DECREMENT:
      return { count: state.count - 1 };
    default:
      throw new Error();
  }
};

const initialState = { count: 0 };

export default function App() {
  const [state, dispatch] = useReducer(reducer, initialState);

  const handleIncreament = () => {
    dispatch({ type: ACTIONS.INCREMENT });
  };

  const handleDecreament = () => {
    dispatch({ type: ACTIONS.DECREMENT });
  };

  return (
    <div className="App">
      <button onClick={handleIncreament}>+</button>
      <h1>{state.count}</h1>
      <button onClick={handleDecreament}>-</button>
    </div>
  );
}


codeSandBox


useReducer 是进阶版的 useState

但当 state 的逻辑和值复杂起来时,或是 state 依赖另一个 state 时

这时候 useReducer 会比 useState 更适合使用

更新 state 不依赖 useEffect,传递 dispatch 并不会在重新 render 时改变。

useReducer 和 Redux 之间的关系?

啊 他们看起来很像馁? 下篇再续~ XD


ref

  1. https://zh-hant.reactjs.org/docs/hooks-reference.html#usereducer
  2. https://zh-hant.reactjs.org/docs/hooks-faq.html

<<:  [DAY 17] _ST25DV16K 动态NFC/RFID tag

>>:  [Day 25] 实作 Redis Plugin 整合 Redis Coroutine Client

Day 29 - 这个游戏制作人疯了吧

Intro 这次写了一个小游戏。里面包含了前几次练习的功能,但是有些东西是用 class 来写出来,...

[Day23] 运用 VS Code 组合键加快编辑速度 - 操作介面篇

过去在看各个前端大神直播或影片的时候,都会发现他们有许多神奇又迅速的操作,但是又不知道该如何做到,今...

[Day 22] JS - 事件委派 Delegation

前言 不知不觉每日的挑战发文活动,也进行到22天了,这件事已经变成每日必做的事,像平日就是工作结束後...

Day17 在React 中使用Material icons

在React中可以插入Material icon组件使用,步骤如下: Material icons网...

[Day19]ISO 27001 附录 A.7 人力资源安全

欸不是,我在验证资讯管理系统,跟人力资源有关系吗? 当然有关系啦! 由於【人】就是公司最重要的资产,...