React Hooks
React Hooks 推出以后,函数组件中经常使用useState保存状态。用过一段时间后发现过多的useState导致页面非常臃肿,具有关联性的状态分散,不利于维护。
基于此,其实React在推出管理状态的Hook时就考虑到了,另一个useReducer就是用于解决上面的现象。那么考虑其使用场景就是必须的了。
何时使用useState或useReducer
一个典型的例子:累加器
import {
useState } from 'react'
const Counter = () => {
const [count, setCount] = useState(0)
const increase = () => {
setCount((count) => count + 1)
}
const decrease = () => {
setCount((count) => count - 1)
}
return (
<div>
<h2>Counter whit useState</h2>
<p>Count: {
count}</p>
<div>
<button type="button" onClick={
increase}>
+
</button>
<button type="button" onClick={
decrease}>
-
</button>
</div>
</div>
)
}
export default Counter
那么将它改造成useReducer来看看:
import {
useReducer } from 'react'
const counterReducer = (state, action) => {
switch (action.type) {
case 'INCREASE':
return {
...state, count: action.count + 1 }
case 'DECREASE':
return {
...state, count: action.count - 1 }
default:
throw new Error()
}
}
const Counter