useReducer 可看做升级版的 useState ,其强大之处在于,可以自定义复杂的响应式变量修改逻辑。
useReducer 语法
useReducer 是 hook 函数
范例 – 计数器

import { useReducer } from "react";
function init(initialCount) {
return { count: initialCount };
}
function reducer(state, action) {
switch (action.type) {
case "increment":
return { count: state.count + 1 };
case "decrement":
return { count: state.count - 1 };
case "reset":
return init(action.payload);
default:
throw new Error();
}
}
function Counter({ initialCount }) {
const [state, dispatch] = useReducer(reducer, initialCount, init);
return (
<>
Count: {state.count}
<button
onClick={() => dispatch({ type: "reset", payload: initialCount })}
>
Reset
</button>
<button onClick={() => dispatch({ type: "decrement" })}>-</button>
<button onClick={() => dispatch({ type: "increment" })}>+</button>
</>
);
}
export default Counter;
import Counter from "./test.jsx";
export default function Index() {
return (
<div>
<Counter initialCount={0} />
</div>
);
}
范例解析
若用 useState 实现,代码如下:
function Counter({initialCount}) {
const [count, setCount] = useState(initialCount);
return (
<>
Count: {count}
<button onClick={() => setCount(initialCount)}>Reset</button>
<button onClick={() => setCount(prevCount => prevCount - 1)}>-</button>
<button onClick={() => setCount(prevCount => prevCount + 1)}>+</button>
</>
);
}
对比可知:
用于对响应式变量进行惰性初始化,传入初始值参数,返回响应式变量的初始值。
function init(initialCount) {
return { count: initialCount };
}
描述复杂的响应式变量修改逻辑
function reducer(state, action) {
switch (action.type) {
case "increment":
return { count: state.count + 1 };
case "decrement":
return { count: state.count - 1 };
case "reset":
return init(action.payload);
default:
throw new Error();
}
}
用于触发响应式变量的改变