来自文档:
[init, 3d 参数] 允许您提取用于计算化简器外部初始状态的逻辑。这对于稍后重置状态以响应操作也很方便。
和代码:
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);
...
}
对我来说看起来不那么啰嗦。
> 编辑 2020 年 7 月:React 文档现在对这个名为lazy initializer
的参数有更好的解释。以其他方式使用此函数可能会导致由于未记录的影响而导致中断性更改。以下答案仍然有效。
据我所知,作为第三个参数的init
函数是initialState
的变压器。
这意味着initialState
不会用作初始状态,而是用作init
函数的参数。这个的回归将是真正的initialState
.在useReducer
初始化行期间避免巨大的参数可能是有用的。
/* Here is the magic. The `initialState` pass to
* `useReducer` as second argument will be hook
* here to init the real `initialState` as return
* of this function
*/
const countInitializer = initialState => {
return {
count: initialState,
otherProp: 0
};
};
const countReducer = state => state; // Dummy reducer
const App = () => {
const [countState /*, countDispatch */] =
React.useReducer(countReducer, 2, countInitializer);
// Note the `countState` will be initialized state direct on first render
return JSON.stringify(countState, null, 2);
}
ReactDOM.render(<App />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
我的理解是,延迟初始化是为特殊情况设计的,即初始化状态的代码是内存密集型或 CPU 密集型的,因此开发人员希望将状态数据的范围保留在组件中。
例如,如果您要设计一个 PhotoPane 组件,该组件包含高清照片以供编辑。
const PhotoPane = (props) => {
const initialPixelData = loadPhoto(props.photoID);
const [pixelData, dispatch] = useReducer(reducerFunc, initialPixelData);
...
}
上面的代码存在严重的性能问题,因为loadPhoto()
被反复调用。如果您不想每次渲染组件时都再次加载照片,直观的反应是将loadPhoto(props.photoID)
移出组件。但这会导致另一个问题。您必须将所有照片加载到上下文或其他地方的内存中,这肯定会造成内存占用。
所以现在是我们引入延迟初始化的时候了。请查看下面的代码。
const PhotoPane = (props) => {
const init = (photoID) => loadPhoto(photoID);
const [pixelData, dispatch] = useReducer(reducerFunc, props.photoID, init);
...
}
init()
函数仅在首次调用useReducer
时执行一次。
实际上useEffect()
钩子都可以达到类似的结果。但延迟初始化仍然是最直接的解决方案。
useReducer接受可选的第三个参数initialAction。如果提供,则在初始渲染期间应用初始操作。
例如:
function Counter({ initialCount }) {
const [state, dispatch] = useReducer(reducer, initialState, {
type: "reset",
payload: initialCount
});
如您所见,第三个参数是在初始渲染期间应用的要执行的初始操作。
例如:代码沙盒示例链接
我认为理解useReducer
的一个好方法是useState
作为useState
具有初始值或惰性初始值设定项的示例。
import { Dispatch, useReducer } from "react";
export function useStateUsingReducer<S>(initialState: S | (() => S)): [S, Dispatch<S>] {
if (typeof initialState === "function") {
return useReducer(
(state: S, newState: S) => (Object.is(state, newState) ? state : newState),
null as unknown as S,
initialState as () => S
);
} else {
return useReducer(
(state: S, newState: S) => (equals(state, newState) ? state : newState),
initialState
);
}
}
而这个更实用的版本是做深度等于,因为useState
只做Object.is
import { equals } from "ramda";
import { Dispatch, useReducer } from "react";
export function useDeepState<S>(initialState: S | (() => S)): [S, Dispatch<S>] {
if (typeof initialState === "function") {
return useReducer(
(state: S, newState: S) => (equals(state, newState) ? state : newState),
null as unknown as S,
initialState as () => S
);
} else {
return useReducer(
(state: S, newState: S) => (equals(state, newState) ? state : newState),
initialState
);
}
}