useImmer
2023年05月28日
一、认识
二、定义
import { produce,Draft, freeze } from "immer";
import { useCallback, useState } from "react";
export type DraftFunction<S> = (draft: Draft<S>) => void;
export type Updater<S> = (arg: S | DraftFunction<S>) => void;
export type ImmerHook<S> = [S, Updater<S>];
export type UseImmer = <S = any>(initialValue: S | (() => S)) => ImmerHook<S>;
export const useImmer:UseImmer = (baseState: any) =>{
const [value, updateValue] = useState(() =>
freeze(typeof baseState === "function" ? baseState() : baseState, true)
);
return [
value,
useCallback((updater: any) => {
if (typeof updater === "function") updateValue(produce(updater));
else updateValue(freeze(updater));
}, []),
];
}
三、使用
import { useImmer } from "./hooks/useImmer";
function App() {
const [form, setForm] = useImmer({
a: "",
b: {
c: {
d: "",
},
},
});
const handleInputChange = (e: any) => {
const { value } = e.target;
setForm((draft)=>{
draft.b.c.d = value;
});
};
return (
<div>
<input value={form.b.c.d} onChange={handleInputChange}></input>
</div>
);
}
export default App;