如果有错误,欢迎留言指教~ Q_Q
上篇提到,如何取得更新後的 state
useReducer
和 useState
都是拿来管理 state
的 hook
一样都可以做到储存和变更 state
的功能,如下:
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>
);
}
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>
);
}
但当 state
的逻辑和值复杂起来时,或是 state 依赖另一个 state 时
这时候 useReducer
会比 useState
更适合使用
更新 state 不依赖 useEffect
,传递 dispatch 并不会在重新 render 时改变。
啊 他们看起来很像馁? 下篇再续~ XD
<<: [DAY 17] _ST25DV16K 动态NFC/RFID tag
>>: [Day 25] 实作 Redis Plugin 整合 Redis Coroutine Client
Intro 这次写了一个小游戏。里面包含了前几次练习的功能,但是有些东西是用 class 来写出来,...
过去在看各个前端大神直播或影片的时候,都会发现他们有许多神奇又迅速的操作,但是又不知道该如何做到,今...
前言 不知不觉每日的挑战发文活动,也进行到22天了,这件事已经变成每日必做的事,像平日就是工作结束後...
在React中可以插入Material icon组件使用,步骤如下: Material icons网...
欸不是,我在验证资讯管理系统,跟人力资源有关系吗? 当然有关系啦! 由於【人】就是公司最重要的资产,...