如果有錯誤,歡迎留言指教~ 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 15 - 用 useReducer 取代 usState !?
標題的 useState 少了 e XD
謝謝眼尖你的(Y)