从文档:
[init, the 3d argument] 让你提取在 reducer 之外计算初始状态的逻辑。这对于稍后响应操作来重置状态也很方便。
和代码:
function init(initialCount) {
return { count: initialCount };
}
function reducer(state, action) {
switch (action.type) {
...
case 'reset':
return init(action.payload);
...
}
}
function Counter({initialCount}) {
const [state, dispatch] = useReducer(reducer, initialCount, init);
...
}
为什么我要重复使用一个常量initialState
?
const initialState = {
count: 5,
};
function reducer(state, action) {
switch (action.type) {
...
case 'reset':
return initialState;
...
}
}
function Counter({initialCount}) {
const [state, dispatch] = useReducer(reducer, initialState);
...
}
对我来说看起来不那么冗长。